Yandex Cloud
Search
Contact UsTry it for free
  • Customer Stories
  • Documentation
  • Blog
  • All Services
  • System Status
  • Marketplace
    • Featured
    • Infrastructure & Network
    • Data Platform
    • AI for business
    • Security
    • DevOps tools
    • Serverless
    • Monitoring & Resources
  • All Solutions
    • By industry
    • By use case
    • Economics and Pricing
    • Security
    • Technical Support
    • Start testing with double trial credits
    • Cloud credits to scale your IT product
    • Gateway to Russia
    • Cloud for Startups
    • Center for Technologies and Society
    • Yandex Cloud Partner program
    • Price calculator
    • Pricing plans
  • Customer Stories
  • Documentation
  • Blog
© 2026 Direct Cursus Technology L.L.C.
Yandex Managed Service for PostgreSQL
  • Getting started
    • All guides
      • Pre-configuration
      • FQDNs of hosts
      • Connecting from applications
      • Code examples
  • Access management
  • Pricing policy
  • Terraform reference
  • Monitoring metrics
  • Audit Trails events
  • Public materials
  • Release notes

In this article:

  • 1C:Enterprise
  • C++ (userver framework)
  • C# EF Core
  • Go
  • Java
  • Node.js
  • ODBC
  • PHP
  • Python
  • R
  • Ruby
  1. Step-by-step guides
  2. Connection
  3. Code examples

Code examples for connecting to a PostgreSQL cluster

Written by
Yandex Cloud
Improved by
Dmitry A.
Updated at March 19, 2026
  • 1C:Enterprise
  • C++ (userver framework)
  • C# EF Core
  • Go
  • Java
  • Node.js
  • ODBC
  • PHP
  • Python
  • R
  • Ruby

The examples were tested in the following environment:

  • Yandex Cloud virtual machine running Ubuntu 20.04 LTS:
    • Bash: 5.0.16.
    • Python: 3.8.2; pip3: 20.0.2.
    • PHP: 7.4.3.
    • OpenJDK: 11.0.8; Maven: 3.6.3.
    • Node.JS: 10.19.0, npm: 6.14.4.
    • Go: 1.13.8.
    • Ruby: 2.7.0p0.
    • unixODBC: 2.3.6.
  • Yandex Cloud virtual machine running Windows Server 2019 Datacenter:
    • PostgreSQL: 13.
    • PowerShell: 5.1.17763.1490 Desktop.
    • .NET 5
    • Microsoft.EntityFrameworkCore 5.0.9
    • Npgsql.EntityFrameworkCore.PostgreSQL 5.0.7

Connections to public PostgreSQL hosts require an SSL certificate. Prepare a certificate before connecting to such hosts.

The examples below assume that the root.crt SSL certificate is located in the following directory:

  • /home/<home_directory>/.postgresql/ for Ubuntu.
  • $HOME\AppData\Roaming\postgresql for Windows.

Connections without an SSL certificate are only supported for hosts that are not publicly accessible. In this case, internal cloud network traffic will not be encrypted during database connections.

You can connect to a cluster using either regular host FQDNs, including a comma-separated list of several FQDNs, or special FQDNs. In our examples, we use the special FQDN pointing to the current master host.

To see code examples with the host FQDN filled in, open the cluster page in the management console and click Connect.

1C:Enterprise1C:Enterprise

If your cluster uses a 1C:Enterprise-optimized PostgreSQL version, specify the following settings:

  • Secure connection: Disabled.
  • DBMS type: PostgreSQL.
  • Database server: c-<cluster_ID>.rw.mdb.yandexcloud.net port=6432.
  • Database name: <DB_name>.
  • Database user: <username>.
  • User password: <password>.
  • Create database if none present: Disabled.

C++ (userver framework)C++ (userver framework)

The asynchronous userver framework provides a rich set of abstractions for creating utilities, services, and microservices in C++. This framework also provides capabilities for PostgreSQL integration.

Before connecting, access the framework using one of the following methods:

  • Create a Yandex Compute Cloud virtual machine using the userver image. This image contains both the framework and all required dependencies.
  • Manually install the framework and all required dependencies.
Connecting without SSL
Connecting with SSL
  1. Create a project from the service template.

  2. Modify the configs/config_vars.yaml configuration file. Specify the PostgreSQL cluster connection string in the dbconnection variable:

    postgres://<username>:<user_password>@c-<cluster_ID>.rw.mdb.yandexcloud.net:6432/<DB_name>
    
  3. Build the project and start the service:

    make build-debug && \
    ./build_debug/pg_service_template -c configs/static_config.yaml --config_vars configs/config_vars.yaml
    
  1. Create a project from the service template.

  2. Modify the configs/config_vars.yaml configuration file. Specify the PostgreSQL cluster connection string in the dbconnection variable:

    postgres://<username>:<user_password>@c-<cluster_ID>.rw.mdb.yandexcloud.net:6432/<DB_name>?ssl=true&sslmode=verify-full
    
  3. Build the project and start the service:

    make build-debug && \
    ./build_debug/pg_service_template -c configs/static_config.yaml --config_vars configs/config_vars.yaml
    

Once started, the service will wait for a POST request from the user. While waiting, the service will periodically check the PostgreSQL cluster's availability by running the SELECT 1 as ping request. You can find this information in the service logs.

Log example of successful cluster connection
tskv ... level=INFO      module=MakeQuerySpan ( userver/postgresql/src/storages/postgres/detail/connection_impl.cpp:647 )
...
db_statement=SELECT 1 AS ping
db_type=postgres
db_instance=********
peer_address=c-********.rw.mdb.yandexcloud.net:6432
...

C# EF CoreC# EF Core

To connect to a cluster, you need the Npgsql package.

Connecting with SSL
using Npgsql;

namespace ConsoleApp
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var host       = "c-<cluster_ID>.rw.mdb.yandexcloud.net";
            var port       = "6432";
            var db         = "<DB_name>";
            var username   = "<username>";
            var password   = "<user_password>";
            var connString = $"Host={host};Port={port};Database={db};Username={username};Password={password};Ssl Mode=VerifyFull;";

            await using var conn = new NpgsqlConnection(connString);
            await conn.OpenAsync();

            await using (var cmd = new NpgsqlCommand("SELECT VERSION();", conn))
            await using (var reader = await cmd.ExecuteReaderAsync())
            {
                while (await reader.ReadAsync())
                {
                    Console.WriteLine(reader.GetInt32(0));
                }
            }
        }
    }
}

GoGo

Before connecting, install the required dependencies:

sudo apt update && sudo apt install --yes golang git && \
go mod init example && go get github.com/jackc/pgx/v4
Connecting without SSL
Connecting with SSL
  1. Code example:

    connect.go

    package main
    
    import (
        "context"
        "fmt"
        "os"
    
        "github.com/jackc/pgx/v4"
    )
    
    const (
      host     = "c-<cluster_ID>.rw.mdb.yandexcloud.net"
      port     = 6432
      user     = "<username>"
      password = "<user_password>"
      dbname   = "<DB_name>"
    )
    
    func main() {
    
        connstring := fmt.Sprintf(
            "host=%s port=%d dbname=%s user=%s password=%s target_session_attrs=read-write",
            host, port, dbname, user, password)
    
        connConfig, err := pgx.ParseConfig(connstring)
        if err != nil {
            fmt.Fprintf(os.Stderr, "Unable to parse config: %v\n", err)
            os.Exit(1)
        }
    
        conn, err := pgx.ConnectConfig(context.Background(), connConfig)
        if err != nil {
            fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
            os.Exit(1)
        }
    
        defer conn.Close(context.Background())
    
        var version string
    
        err = conn.QueryRow(context.Background(), "select version()").Scan(&version)
        if err != nil {
            fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
            os.Exit(1)
        }
    
        fmt.Println(version)
    }
    
  2. Connecting:

    go run connect.go
    
  1. Code example:

    connect.go

    package main
    
    import (
        "context"
        "crypto/tls"
        "crypto/x509"
        "fmt"
        "io/ioutil"
        "os"
    
        "github.com/jackc/pgx/v4"
    )
    
    const (
      host     = "c-<cluster_ID>.rw.mdb.yandexcloud.net"
      port     = 6432
      user     = "<username>"
      password = "<user_password>"
      dbname   = "<DB_name>"
      ca       = "/home/<home_directory>/.postgresql/root.crt"
    )
    
    func main() {
    
        rootCertPool := x509.NewCertPool()
        pem, err := ioutil.ReadFile(ca)
        if err != nil {
            panic(err)
        }
    
        if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
            panic("Failed to append PEM.")
        }
    
        connstring := fmt.Sprintf(
            "host=%s port=%d dbname=%s user=%s password=%s sslmode=verify-full target_session_attrs=read-write",
            host, port, dbname, user, password)
    
        connConfig, err := pgx.ParseConfig(connstring)
        if err != nil {
            fmt.Fprintf(os.Stderr, "Unable to parse config: %v\n", err)
            os.Exit(1)
        }
    
        connConfig.TLSConfig = &tls.Config{
            RootCAs:            rootCertPool,
            ServerName: "c-<cluster_ID>.rw.mdb.yandexcloud.net",
        }
    
        conn, err := pgx.ConnectConfig(context.Background(), connConfig)
        if err != nil {
            fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
            os.Exit(1)
        }
    
        defer conn.Close(context.Background())
    
        var version string
    
        err = conn.QueryRow(context.Background(), "select version()").Scan(&version)
        if err != nil {
            fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
            os.Exit(1)
        }
    
        fmt.Println(version)
    }
    

    For this connection method, you must specify the full path to the PostgreSQL root.crt certificate in the ca variable.

  2. Connecting:

    go run connect.go
    

JavaJava

Before connecting:

  1. Install the dependencies:

    sudo apt update && sudo apt install --yes default-jdk maven
    
  2. Create a directory for the Maven project:

    cd ~/ && mkdir -p project/src/java/com/example && cd project/
    
  3. Create a configuration file for Maven:

    pom.xml
    <?xml version="1.0" encoding="utf-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.example</groupId>
      <artifactId>app</artifactId>
      <packaging>jar</packaging>
      <version>0.1.0</version>
      <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.postgresql</groupId>
          <artifactId>postgresql</artifactId>
          <version>42.2.16</version>
        </dependency>
      </dependencies>
      <build>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <sourceDirectory>src</sourceDirectory>
        <resources>
          <resource>
            <directory>src</directory>
          </resource>
        </resources>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
              <execution>
                <goals>
                  <goal>attached</goal>
                </goals>
                <phase>package</phase>
                <configuration>
                  <descriptorRefs>
                    <descriptorRef>
                    jar-with-dependencies</descriptorRef>
                  </descriptorRefs>
                  <archive>
                    <manifest>
                      <mainClass>com.example.App</mainClass>
                    </manifest>
                  </archive>
                </configuration>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.1.0</version>
            <configuration>
              <archive>
                <manifest>
                  <mainClass>com.example.App</mainClass>
                </manifest>
              </archive>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
    

    Current dependency version for Maven: postgresql.

Connecting without SSL
Connecting with SSL
  1. Code example:

    src/java/com/example/App.java

    package com.example;
    
    import java.sql.*;
    
    public class App {
      public static void main(String[] args) {
        String DB_URL     = "jdbc:postgresql://c-<cluster_ID>.rw.mdb.yandexcloud.net:6432/<DB_name>?targetServerType=master&ssl=false&sslmode=disable";
        String DB_USER    = "<username>";
        String DB_PASS    = "<user_password>";
    
        try {
          Class.forName("org.postgresql.Driver");
    
          Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
          ResultSet q = conn.createStatement().executeQuery("SELECT version()");
          if(q.next()) {System.out.println(q.getString(1));}
    
          conn.close();
        }
        catch(Exception ex) {ex.printStackTrace();}
      }
    }
    
  2. Building and connecting:

    mvn clean package && \
    java -jar target/app-0.1.0-jar-with-dependencies.jar
    
  1. Code example:

    src/java/com/example/App.java

    package com.example;
    
    import java.sql.*;
    
    public class App {
      public static void main(String[] args) {
        String DB_URL     = "jdbc:postgresql://c-<cluster_ID>.rw.mdb.yandexcloud.net:6432/<DB_name>?targetServerType=master&ssl=true&sslmode=verify-full";
        String DB_USER    = "<username>";
        String DB_PASS    = "<user_password>";
    
        try {
          Class.forName("org.postgresql.Driver");
    
          Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
          ResultSet q = conn.createStatement().executeQuery("SELECT version()");
          if(q.next()) {System.out.println(q.getString(1));}
    
          conn.close();
        }
        catch(Exception ex) {ex.printStackTrace();}
      }
    }
    
  2. Building and connecting:

    mvn clean package && \
    java -jar target/app-0.1.0-jar-with-dependencies.jar
    

Node.jsNode.js

Before connecting, install the required dependencies:

sudo apt update && sudo apt install --yes nodejs npm && \
npm install pg
Connecting without SSL
Connecting with SSL

app.js

"use strict";
const pg = require("pg");

const config = {
    connectionString:
        "postgres://<username>:<user_password>@c-<cluster_ID>.rw.mdb.yandexcloud.net:6432/<DB_name>"
};

const conn = new pg.Client(config);

conn.connect((err) => {
    if (err) throw err;
});
conn.query("SELECT version()", (err, q) => {
    if (err) throw err;
    console.log(q.rows[0]);
    conn.end();
});

app.js

"use strict";
const fs = require("fs");
const pg = require("pg");

const config = {
    connectionString:
        "postgres://<username>:<user_password>@c-<cluster_ID>.rw.mdb.yandexcloud.net:6432/<DB_name>",
    ssl: {
        rejectUnauthorized: true,
        ca: fs
            .readFileSync("/home/<home_directory>/.postgresql/root.crt")
            .toString(),
    },
};

const conn = new pg.Client(config);

conn.connect((err) => {
    if (err) throw err;
});
conn.query("SELECT version()", (err, q) => {
    if (err) throw err;
    console.log(q.rows[0]);
    conn.end();
});

For this connection method, you must specify the full path to the PostgreSQL root.crt certificate in the ca variable.

You can get the cluster ID from the cluster list.

Connecting:

node app.js

ODBCODBC

Before connecting, install the required dependencies:

sudo apt update && sudo apt install --yes unixodbc odbc-postgresql

The system will automatically register the PostgreSQL ODBC driver in /etc/odbcinst.ini.

Connecting without SSL
Connecting with SSL
  1. Code example:

    /etc/odbc.ini

    [postgresql]
    Driver=PostgreSQL Unicode
    Servername=c-<cluster_ID>.rw.mdb.yandexcloud.net
    Username=<username>
    Password=<user_password>
    Database=<DB_name>
    Port=6432
    Pqopt=target_session_attrs=read-write
    
  2. Connecting:

    isql -v postgresql
    

    Once connected to the DBMS, run the SELECT version(); command.

  1. Code example:

    /etc/odbc.ini

    [postgresql]
    Driver=PostgreSQL Unicode
    Servername=c-<cluster_ID>.rw.mdb.yandexcloud.net
    Username=<username>
    Password=<user_password>
    Database=<DB_name>
    Port=6432
    Pqopt=target_session_attrs=read-write
    Sslmode=verify-full
    
  2. Connecting:

    isql -v postgresql
    

    Once connected to the DBMS, run the SELECT version(); command.

PHPPHP

Before connecting, install the required dependencies:

sudo apt update && sudo apt install --yes php php-pgsql
Connecting without SSL
Connecting with SSL
  1. Code example:

    connect.php

    <?php
      $conn = pg_connect("
          host=c-<cluster_ID>.rw.mdb.yandexcloud.net
          port=6432
          sslmode=disable
          dbname=<DB_name>
          user=<username>
          password=<user_password>
          target_session_attrs=read-write
      ");
    
    $q = pg_query($conn, "SELECT version()");
    $result = pg_fetch_row($q);
    echo $result[0];
    
    pg_close($conn);
    ?>
    
  2. Connecting:

    php connect.php
    
  1. Code example:

    connect.php

    <?php
      $conn = pg_connect("
          host=c-<cluster_ID>.rw.mdb.yandexcloud.net
          port=6432
          sslmode=verify-full
          dbname=<DB_name>
          user=<username>
          password=<user_password>
          target_session_attrs=read-write
      ");
    
    $q = pg_query($conn, "SELECT version()");
    $result = pg_fetch_row($q);
    echo $result[0];
    
    pg_close($conn);
    ?>
    
  2. Connecting:

    php connect.php
    

PythonPython

Before connecting, install the required dependencies:

sudo apt update && sudo apt install -y python3 python3-pip && \
pip3 install psycopg2-binary
Connecting without SSL
Connecting with SSL
  1. Code example:

    connect.py

    import psycopg2
    
    conn = psycopg2.connect("""
        host=c-<cluster_ID>.rw.mdb.yandexcloud.net
        port=6432
        sslmode=disable
        dbname=<DB_name>
        user=<username>
        password=<user_password>
        target_session_attrs=read-write
    """)
    
    q = conn.cursor()
    q.execute('SELECT version()')
    
    print(q.fetchone())
    
    conn.close()
    
  2. Connecting:

    python3 connect.py
    
  1. Code example:

    connect.py

    import psycopg2
    
    conn = psycopg2.connect("""
        host=c-<cluster_ID>.rw.mdb.yandexcloud.net
        port=6432
        sslmode=verify-full
        dbname=<DB_name>
        user=<username>
        password=<user_password>
        target_session_attrs=read-write
    """)
    
    q = conn.cursor()
    q.execute('SELECT version()')
    
    print(q.fetchone())
    
    conn.close()
    
  2. Connecting:

    python3 connect.py
    

RR

Before connecting:

  1. Install the dependencies:

    sudo apt update && sudo apt install libpq-dev r-base --yes
    
  2. Install the RPostgres library:

    sudo R --interactive
    install.packages("RPostgres")
    quit()
    
Connecting without SSL
Connecting with SSL
  1. Code example:

    connect.r

    library(DBI)
    
    conn <- dbConnect(RPostgres::Postgres(),
        dbname="<DB_name>",
        host="c-<cluster_ID>.rw.mdb.yandexcloud.net",
        port=6432,
        user="<username>",
        password="<user_password>"
    )
    
    res <- dbSendQuery(conn, "SELECT VERSION();")
    dbFetch(res)
    dbClearResult(res)
    
    dbDisconnect(conn)
    
  2. Connecting:

    R connect.r
    
  1. Code example:

    connect.r

    library(DBI)
    
    conn <- dbConnect(RPostgres::Postgres(),
        dbname="<DB_name>",
        host="c-<cluster_ID>.rw.mdb.yandexcloud.net",
        port=6432,
        sslmode="verify-full",
        user="<username>",
        password="<user_password>"
    )
    
    res <- dbSendQuery(conn, "SELECT VERSION();")
    dbFetch(res)
    dbClearResult(res)
    
    dbDisconnect(conn)
    
  2. Connecting:

    R connect.r
    

RubyRuby

Before connecting, install the required dependencies:

sudo apt update && sudo apt install --yes ruby ruby-pg
Connecting without SSL
Connecting with SSL
  1. Code example:

    connect.rb

    require "pg"
    
    conn = PG.connect("
            host=c-<cluster_ID>.rw.mdb.yandexcloud.net
            port=6432
            dbname=<DB_name>
            user=<username>
            password=<user_password>
            target_session_attrs=read-write
            sslmode=disable
    ")
    
    q = conn.exec("SELECT version()")
    puts q.getvalue 0, 0
    
    conn.close()
    
  2. Connecting:

    ruby connect.rb
    
  1. Code example:

    connect.rb

    require "pg"
    
    conn = PG.connect("
            host=c-<cluster_ID>.rw.mdb.yandexcloud.net
            port=6432
            dbname=<DB_name>
            user=<username>
            password=<user_password>
            target_session_attrs=read-write
            sslmode=verify-full
    ")
    
    q = conn.exec("SELECT version()")
    puts q.getvalue 0, 0
    
    conn.close()
    
  2. Connecting:

    ruby connect.rb
    

If your cluster connection and test query are successful, you will see the PostgreSQL version. One exception is the userver framework example, where the SELECT 1 as ping test query will be executed for periodic PostgreSQL cluster availability checks.

Was the article helpful?

Previous
Connecting from applications
Next
SQL queries in Yandex WebSQL
© 2026 Direct Cursus Technology L.L.C.