Code examples for connecting to a PostgreSQL cluster
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.
- Bash:
- 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
- PostgreSQL:
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\postgresqlfor 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
1C: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)
The asynchronous userver
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
.
-
Create a project from the service template
. -
Modify the
configs/config_vars.yamlconfiguration file. Specify the PostgreSQL cluster connection string in thedbconnectionvariable:postgres://<username>:<user_password>@c-<cluster_ID>.rw.mdb.yandexcloud.net:6432/<DB_name> -
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
-
Create a project from the service template
. -
Modify the
configs/config_vars.yamlconfiguration file. Specify the PostgreSQL cluster connection string in thedbconnectionvariable:postgres://<username>:<user_password>@c-<cluster_ID>.rw.mdb.yandexcloud.net:6432/<DB_name>?ssl=true&sslmode=verify-full -
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 Core
To connect to a cluster, you need the Npgsql
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));
}
}
}
}
}
Go
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
-
Code example:
connect.gopackage 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) } -
Connecting:
go run connect.go
-
Code example:
connect.gopackage 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.crtcertificate in thecavariable. -
Connecting:
go run connect.go
Java
Before connecting:
-
Install the dependencies:
sudo apt update && sudo apt install --yes default-jdk maven -
Create a directory for the Maven project:
cd ~/ && mkdir -p project/src/java/com/example && cd project/ -
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
.
-
Code example:
src/java/com/example/App.javapackage 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();} } } -
Building and connecting:
mvn clean package && \ java -jar target/app-0.1.0-jar-with-dependencies.jar
-
Code example:
src/java/com/example/App.javapackage 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();} } } -
Building and connecting:
mvn clean package && \ java -jar target/app-0.1.0-jar-with-dependencies.jar
Node.js
Before connecting, install the required dependencies:
sudo apt update && sudo apt install --yes nodejs npm && \
npm install pg
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
ODBC
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.
-
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 -
Connecting:
isql -v postgresqlOnce connected to the DBMS, run the
SELECT version();command.
-
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 -
Connecting:
isql -v postgresqlOnce connected to the DBMS, run the
SELECT version();command.
PHP
Before connecting, install the required dependencies:
sudo apt update && sudo apt install --yes php php-pgsql
-
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); ?> -
Connecting:
php connect.php
-
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); ?> -
Connecting:
php connect.php
Python
Before connecting, install the required dependencies:
sudo apt update && sudo apt install -y python3 python3-pip && \
pip3 install psycopg2-binary
-
Code example:
connect.pyimport 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() -
Connecting:
python3 connect.py
-
Code example:
connect.pyimport 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() -
Connecting:
python3 connect.py
R
Before connecting:
-
Install the dependencies:
sudo apt update && sudo apt install libpq-dev r-base --yes -
Install the RPostgres
library:sudo R --interactive install.packages("RPostgres") quit()
-
Code example:
connect.rlibrary(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) -
Connecting:
R connect.r
-
Code example:
connect.rlibrary(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) -
Connecting:
R connect.r
Ruby
Before connecting, install the required dependencies:
sudo apt update && sudo apt install --yes ruby ruby-pg
-
Code example:
connect.rbrequire "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() -
Connecting:
ruby connect.rb
-
Code example:
connect.rbrequire "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() -
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.