# Connect to PostgreSQL

{/* GENERATED by scripts/gen-connect-pages.mjs from data/connect-catalogue. Do not edit: run `npm run gen:connect`. */}

Every snippet on this page connects to a managed PostgreSQL over TLS and checks that the server is really your database. They are the same snippets the **Connect** tab of your database shows, where the address, user and certificate path are already filled in.

Replace:

| In the snippet | With |
|---|---|
| `HOST`, `USER` | the address and user on the Connect tab |
| `DATABASE` | your database name |
| `<password>` | the password (**Reveal** on the Connect tab fills it in for you) |
| `CA_FILE` | `/etc/zaroz/ca/database-ca.pem` in an app running on Zaroz; elsewhere, the full path of the certificate you download on the Connect tab |

Why TLS, and what Zaroz sets up in your apps for you: [Connect an app to a managed database](/guides/databases/connect-tls).

## Connection string and environment

<a id="database_url"></a>

### DATABASE_URL

```bash
DATABASE_URL=postgres://USER:<password>@HOST:5432/DATABASE?sslmode=verify-full&sslrootcert=CA_FILE
```

- TLS is required: sslmode=verify-full checks the certificate and the host name against the CA bundle in sslrootcert.
- libpq (psql, psycopg), node-postgres, pgx and sqlx read this URL as is. Prisma and JDBC do not: use their tabs.

Through the connection pooler:

- Through the pooler in transaction mode, prepared statements are not kept between transactions; turn them off in your driver.

<a id="env_vars"></a>

### .env (PG* variables)

```bash
PGHOST=HOST
PGPORT=5432
PGDATABASE=DATABASE
PGUSER=USER
PGPASSWORD=<password>
PGSSLMODE=verify-full
PGSSLROOTCERT=CA_FILE
```

- libpq clients (psql, pg_dump, psycopg, many others) read these variables without any code.
- TLS is required: PGSSLMODE=verify-full with PGSSLROOTCERT verifies the server.

## Command line

<a id="psql"></a>

### psql

```bash
PGPASSWORD='<password>' psql "host=HOST port=5432 dbname=DATABASE user=USER sslmode=verify-full sslrootcert=CA_FILE" -c 'SELECT 1'
```

- TLS is required: sslmode=verify-full with sslrootcert verifies the server certificate.

## Node.js

<a id="node_pg"></a>

### pg (node-postgres)

```javascript
import fs from "node:fs";
import pg from "pg";

const client = new pg.Client({
  host: "HOST",
  port: 5432,
  user: "USER",
  password: "<password>",
  database: "DATABASE",
  ssl: { ca: fs.readFileSync("CA_FILE", "utf8") },
});
await client.connect();
console.log((await client.query("SELECT 1 AS ok")).rows);
await client.end();
```

- TLS is required: pass the CA bundle as ssl.ca; node-postgres then verifies the server certificate and host name.
- Run as an ES module ("type": "module" or a .mjs file).

<a id="node_postgres_js"></a>

### postgres.js

```javascript
import fs from "node:fs";
import postgres from "postgres";

const sql = postgres({
  host: "HOST",
  port: 5432,
  username: "USER",
  password: "<password>",
  database: "DATABASE",
  ssl: { ca: fs.readFileSync("CA_FILE", "utf8"), rejectUnauthorized: true },
});
console.log(await sql`SELECT 1 AS ok`);
await sql.end();
```

- TLS is required: ssl.ca plus rejectUnauthorized verifies the server.

Through the connection pooler:

- Through the pooler in transaction mode set prepare: false.

<a id="node_prisma"></a>

### Prisma

```prisma
# .env
# Prisma 7: the client connects through node-postgres (DATABASE_URL);
# the CLI (migrate, db push) through the schema engine (DIRECT_URL).
DATABASE_URL="postgresql://USER:<password>@HOST:5432/DATABASE?sslmode=verify-full&sslrootcert=CA_FILE"
DIRECT_URL="postgresql://USER:<password>@HOST:5432/DATABASE?sslmode=require&sslcert=CA_FILE&sslaccept=strict"

// prisma.config.ts
import "dotenv/config";
import { defineConfig, env } from "prisma/config";

export default defineConfig({
  schema: "prisma/schema.prisma",
  datasource: { url: env("DIRECT_URL") },
});

// your app
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "./generated/prisma/client";

const prisma = new PrismaClient({
  adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
});

// Prisma 6: schema.prisma keeps url = env("DIRECT_URL") and needs no adapter.
```

- TLS is required: through the adapter, node-postgres verifies the server with sslmode=verify-full and sslrootcert; the CLI uses sslcert with sslaccept=strict, without which Prisma accepts any certificate.
- Give sslcert an absolute path: a relative one is resolved from the prisma folder, not from where you run the command.

Through the connection pooler:

- Through the pooler in transaction mode, Prisma 6 needs &pgbouncer=true on its URL; the Prisma 7 adapter needs nothing.

<a id="node_drizzle"></a>

### Drizzle ORM

```typescript
import fs from "node:fs";
import { drizzle } from "drizzle-orm/node-postgres";
import { sql } from "drizzle-orm";
import pg from "pg";

const pool = new pg.Pool({
  host: "HOST",
  port: 5432,
  user: "USER",
  password: "<password>",
  database: "DATABASE",
  ssl: { ca: fs.readFileSync("CA_FILE", "utf8") },
});
const db = drizzle(pool);
console.log((await db.execute(sql`SELECT 1 AS ok`)).rows);
await pool.end();
```

- TLS is required: Drizzle uses node-postgres, so the CA bundle goes in ssl.ca.

## Python

<a id="python_psycopg"></a>

### psycopg 3

```python
import psycopg

with psycopg.connect(
    host="HOST",
    port=5432,
    dbname="DATABASE",
    user="USER",
    password="<password>",
    sslmode="verify-full",
    sslrootcert="CA_FILE",
) as conn:
    print(conn.execute("SELECT 1").fetchone())
```

- TLS is required: sslmode=verify-full with sslrootcert verifies the server certificate and host name.

<a id="python_sqlalchemy"></a>

### SQLAlchemy

```python
from sqlalchemy import create_engine, text

engine = create_engine(
    "postgresql+psycopg://USER:<password>@HOST:5432/DATABASE",
    connect_args={"sslmode": "verify-full", "sslrootcert": "CA_FILE"},
)
with engine.connect() as conn:
    print(conn.execute(text("SELECT 1")).scalar())
```

- TLS is required: connect_args pass sslmode and sslrootcert through to psycopg.

<a id="python_django"></a>

### Django

```python
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "HOST": "HOST",
        "PORT": "5432",
        "NAME": "DATABASE",
        "USER": "USER",
        "PASSWORD": "<password>",
        "OPTIONS": {"sslmode": "verify-full", "sslrootcert": "CA_FILE"},
    }
}
```

- TLS is required: OPTIONS passes sslmode and sslrootcert to the driver.

Through the connection pooler:

- Through the pooler in transaction mode set DISABLE_SERVER_SIDE_CURSORS = True in the database settings.

## Go

<a id="go_pgx"></a>

### pgx

```go
package main

import (
	"context"
	"fmt"

	"github.com/jackc/pgx/v5"
)

func main() {
	ctx := context.Background()
	conn, err := pgx.Connect(ctx, "postgres://USER:<password>@HOST:5432/DATABASE?sslmode=verify-full&sslrootcert=CA_FILE")
	if err != nil {
		panic(err)
	}
	defer conn.Close(ctx)

	var one int
	if err := conn.QueryRow(ctx, "SELECT 1").Scan(&one); err != nil {
		panic(err)
	}
	fmt.Println(one)
}
```

- TLS is required: sslmode=verify-full with sslrootcert in the connection string verifies the server.

Through the connection pooler:

- Through the pooler in transaction mode use pgx.QueryExecModeCacheDescribe or QueryExecModeExec instead of the default prepared statements.

## PHP

<a id="php_pdo"></a>

### PDO

```php
<?php
$dsn = "pgsql:host=HOST;port=5432;dbname=DATABASE;sslmode=verify-full;sslrootcert=CA_FILE";
$pdo = new PDO($dsn, "USER", "<password>", [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
echo $pdo->query("SELECT 1")->fetchColumn(), PHP_EOL;
```

- TLS is required: sslmode=verify-full with sslrootcert in the DSN verifies the server.

<a id="php_laravel"></a>

### Laravel (.env)

```bash
DB_CONNECTION=pgsql
DB_HOST=HOST
DB_PORT=5432
DB_DATABASE=DATABASE
DB_USERNAME=USER
DB_PASSWORD=<password>
DB_SSLMODE=verify-full
DB_SSLROOTCERT=CA_FILE

# config/database.php, in the pgsql connection ('sslmode' already reads DB_SSLMODE):
#   'sslrootcert' => env('DB_SSLROOTCERT'),
```

- TLS is required: Laravel puts sslmode and sslrootcert into the pgsql DSN, and libpq then verifies the server certificate and host name.

## Java and .NET

<a id="java_jdbc"></a>

### JDBC

```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {
    public static void main(String[] args) throws Exception {
        String url = "jdbc:postgresql://HOST:5432/DATABASE?sslmode=verify-full&sslrootcert=CA_FILE";
        try (Connection connection = DriverManager.getConnection(url, "USER", "<password>");
             Statement statement = connection.createStatement();
             ResultSet rows = statement.executeQuery("SELECT 1")) {
            rows.next();
            System.out.println(rows.getInt(1));
        }
    }
}
```

- TLS is required: sslmode=verify-full with sslrootcert verifies the server; the CA file must be PEM.
- JDBC does not read PGSSLROOTCERT, so sslrootcert stays in the URL even inside Zaroz.

<a id="dotnet_npgsql"></a>

### Npgsql

```csharp
using Npgsql;

var connectionString = "Host=HOST;Port=5432;Database=DATABASE;Username=USER;Password=<password>;SSL Mode=VerifyFull;Root Certificate=CA_FILE";
await using var connection = new NpgsqlConnection(connectionString);
await connection.OpenAsync();
await using var command = new NpgsqlCommand("SELECT 1", connection);
Console.WriteLine(await command.ExecuteScalarAsync());
```

- TLS is required: SSL Mode=VerifyFull with Root Certificate verifies the server.

## Rust

<a id="rust_sqlx"></a>

### sqlx

```rust
use sqlx::postgres::{PgConnectOptions, PgSslMode};
use sqlx::Connection;

#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
    let options = PgConnectOptions::new()
        .host("HOST")
        .port(5432)
        .username("USER")
        .password("<password>")
        .database("DATABASE")
        .ssl_mode(PgSslMode::VerifyFull)
        .ssl_root_cert("CA_FILE");
    let mut connection = sqlx::PgConnection::connect_with(&options).await?;
    let one: i32 = sqlx::query_scalar("SELECT 1").fetch_one(&mut connection).await?;
    println!("{one}");
    Ok(())
}
```

- TLS is required: PgSslMode::VerifyFull with ssl_root_cert verifies the server.
- Enable a TLS feature of sqlx (tls-rustls or tls-native-tls) next to runtime-tokio.

<a id="rust_tokio_postgres"></a>

### tokio-postgres

```rust
use native_tls::{Certificate, TlsConnector};
use postgres_native_tls::MakeTlsConnector;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let ca = Certificate::from_pem(&std::fs::read("CA_FILE")?)?;
    let tls = MakeTlsConnector::new(TlsConnector::builder().add_root_certificate(ca).build()?);
    let (client, connection) = tokio_postgres::connect(
        "host=HOST port=5432 user=USER password=<password> dbname=DATABASE sslmode=require",
        tls,
    )
    .await?;
    tokio::spawn(connection);
    let row = client.query_one("SELECT 1", &[]).await?;
    println!("{}", row.get::<_, i32>(0));
    Ok(())
}
```

- TLS is required: sslmode=require makes tokio-postgres insist on TLS; the native-tls connector verifies the server against the CA bundle and the host name.

## Desktop tools

<a id="gui_tableplus"></a>

### TablePlus

```text
Connection type: PostgreSQL
Host: HOST
Port: 5432
User: USER
Password: <password>
Database: DATABASE
SSL mode: VERIFY-FULL
SSL keys, CA Cert: CA_FILE
```

- TLS is required: choose VERIFY-FULL and select the CA bundle.

<a id="gui_dbeaver"></a>

### DBeaver

```text
Driver: PostgreSQL
Host: HOST
Port: 5432
Database: DATABASE
Username: USER
Password: <password>
SSL tab: Use SSL, CA Certificate CA_FILE, Advanced > SSL mode verify-full (leave SSL Factory empty)
```

- TLS is required: on the SSL tab turn on Use SSL, select the CA bundle as CA Certificate and set the SSL mode to verify-full.

<a id="gui_pgadmin"></a>

### pgAdmin

```text
Host name/address: HOST
Port: 5432
Maintenance database: DATABASE
Username: USER
Password: <password>
Parameters tab: SSL mode verify-full, add Root certificate CA_FILE
```

- TLS is required: on the Parameters tab set SSL mode to verify-full and add the CA bundle as Root certificate.
