Connecting to a database in a PostgreSQL cluster
- Configuring security groups
- Obtaining an SSL certificate
- PostgreSQL host FQDN
- Special FQDNs
- Selecting an FQDN and cluster connection method
- Connecting from graphical IDEs
- Connecting with IAM authentication
- Connecting from Yandex WebSQL
- Connecting from pgAdmin 4
- Connecting from Looker Studio
- Before you connect from a Docker container
- Examples of connection strings
You can connect to Managed Service for PostgreSQL cluster hosts:
-
Via the internet, if you configured public access for the host. You can connect over the internet in the following ways:
- Using an SSL connection.
- Using IAM authentication.
-
From Yandex Cloud virtual machines located in the same cloud network. For hosts without public access, SSL is not required to connect to them from these virtual machines.
-
From the Serverless Containers container. For hosts without public access, the container must reside in the same cloud network.
Warning
If only some cluster hosts have public access, an automatic master failover can make the master host unreachable from the internet.
Configuring security groups
To connect to a cluster, security groups must include rules allowing traffic from certain ports, IP addresses, or from other security groups.
Rule settings depend on the chosen connection method:
Configure all cluster security groups to allow incoming traffic on port 6432 from any IP address. To do this, create the following ingress rule:
- Port range:
6432 - Protocol:
TCP - Source:
CIDR - CIDR blocks:
0.0.0.0/0
-
Configure all cluster security groups to allow incoming traffic on port 6432 from the target VM’s security group. To do this, create the following ingress rule in these groups:
- Port range:
6432 - Protocol:
TCP - Source:
Security group - Security group: If your cluster and VM share the same security group, select
Current(Self). Otherwise, specify the VM security group.
- Port range:
-
Configure the VM security group to allow VM connections and traffic between the VM and cluster hosts.
For example, you can set the following rules for your VM:
-
For incoming traffic:
- Port range:
22 - Protocol:
TCP - Source:
CIDR - CIDR blocks:
0.0.0.0/0
This rule allows inbound VM connections over SSH.
- Port range:
-
For outgoing traffic:
- Port range:
0-65535 - Protocol:
Any(Any) - Destination name:
CIDR - CIDR blocks:
0.0.0.0/0
This rule permits all outbound traffic, allowing you to connect to the cluster and install any necessary certificates and tools on your VM.
- Port range:
-
Note
You can specify more granular security group rules, such as allowing traffic only in specific subnets.
Make sure to configure the security groups correctly for all subnets where the cluster hosts will reside. With incomplete or incorrect security group settings, you may lose access to the cluster if a manual or automatic master failover occurs.
For more information about security groups, see Security groups.
Obtaining an SSL certificate
Publicly accessible PostgreSQL hosts only support encrypted connections. You must obtain an SSL certificate to connect to them:
mkdir -p ~/.postgresql && \
wget "https://storage.yandexcloud.net/cloud-certs/CA.pem" \
--output-document ~/.postgresql/root.crt && \
chmod 0655 ~/.postgresql/root.crt
The certificate will be saved to the ~/.postgresql/root.crt file.
mkdir $HOME\.postgresql; curl.exe -o $HOME\.postgresql\root.crt https://storage.yandexcloud.net/cloud-certs/CA.pem
The certificate will be saved to the $HOME\.postgresql\root.crt file.
Your corporate security policies and antivirus software may block the certificate download. For more information, see FAQ.
To use graphical IDEs, save a certificate
PostgreSQL host FQDN
To connect to a host, you need its fully qualified domain name (FQDN). You can get it using one of the following methods:
-
In the management console
, copy the command for connecting to the cluster (it contains the host’s FQDN). To get the command, go to the cluster page and click Connect. -
Look up the FQDN in the management console:
- Navigate to the cluster page.
- Navigate to Hosts.
- Copy the Host FQDN column value.
Cluster hosts also use special FQDNs.
Special FQDNs
Alongside regular FQDNs, Managed Service for PostgreSQL offers special FQDNs that can be also used for cluster connections.
In multiple-host clusters, special FQDNs may for some time (up to 10 minutes) point to the old host, even if it has changed its role (e.g., from a master to a replica). If using a special FQDN which points to the current master, some write requests may fail if routed to the replica. This is because it takes time to update DNS records for special FQDNs. If your write request returns an error, repeat it later.
Current master
An FQDN in c-<cluster_ID>.rw.mdb.yandexcloud.net format always points to the current master host in the cluster. You can get the cluster ID from the folder’s cluster list.
When connecting to this FQDN, you can perform read and write operations.
Warning
Use master host special FQDN-based connections only for processes that can cope with database being unavailable for writing for up to 10 minutes.
Most recent replica
An FQDN in c-<cluster_ID>.ro.mdb.yandexcloud.net format points to the most up-to-date replica. You can get the cluster ID with the list of clusters in the folder.
Specifics:
- When connecting to this FQDN, you can only perform read operations.
- If there are no active replicas in the cluster, this FQDN will point to the current master host.
- Replicas with a manually configured replication source cannot be selected as most up-to-date replicas when using this FQDN.
Selecting an FQDN and cluster connection method
You can connect to a cluster using its host FQDNs or special FQDNs. If the cluster consists of several hosts, keep in mind that the current master can become a replica at any moment, and vice versa.
Warning
If automatic failover promotes a host without public access to master or most up-to-date replica, that host will be unreachable from the internet. To avoid this, enable public access for all cluster hosts.
Use one of the following methods to connect to the master host with read and write access:
-
Connect using the special FQDN pointing to the current master.
After a master failover, this FQDN may temporarily point to the previous master, now a replica, due to the time required for the DNS record to update.
Therefore, applications using this FQDN must be designed to handle temporary master unavailability. For example, they should retry write requests after a short delay.
Connection example
In this example, we use the
c9qash3nb1v9********cluster ID:psql "host=c-c9qash3nb1v9********.rw.mdb.yandexcloud.net \ port=6432 \ sslmode=verify-full \ dbname=<DB_name> \ user=<username>" -
Connect by listing all cluster hosts and specifying
target_session_attrs=read-write.Connection example
Here, we list all the cluster’s hosts.
The host IDs are
rc1a-be***.mdb.yandexcloud.net,rc1b-5r***.mdb.yandexcloud.net, andrc1d-t4***.mdb.yandexcloud.net:psql "host=rc1a-be***.mdb.yandexcloud.net,rc1b-5r***.mdb.yandexcloud.net,rc1d-t4***.mdb.yandexcloud.net \ port=6432 \ sslmode=verify-full \ dbname=<DB_name> \ user=<username> \ target_session_attrs=read-write"
Use one of the following methods to connect to the host with read access:
-
Connect using a special FQDN pointing to the most up-to-date replica.
Connection example
In this example, we use the
c9qash3nb1v9********cluster ID:psql "host=c-c9qash3nb1v9********.ro.mdb.yandexcloud.net \ port=6432 \ sslmode=verify-full \ dbname=<DB_name> \ user=<username>" -
Connect by listing all cluster hosts and specifying
target_session_attrs=any.Connection example
Here, we list all the cluster’s hosts.
The host IDs are
rc1a-be***.mdb.yandexcloud.net,rc1b-5r***.mdb.yandexcloud.net, andrc1d-t4***.mdb.yandexcloud.net:psql "host=rc1a-be***.mdb.yandexcloud.net,rc1b-5r***.mdb.yandexcloud.net,rc1d-t4***.mdb.yandexcloud.net \ port=6432 \ sslmode=verify-full \ dbname=<DB_name> \ user=<username> \ target_session_attrs=any"
Note
You can use the target_session_attrs setting when connecting via a client utilizing the libpq library.
Support for the read-write value in this setting was introduced in libpq version 10
How to update the library version used by psql
- For Debian-based Linux distributions, install the
postgresql-client-10package or a newer version from the official APT repository (or another source of your choice). - For RPM-based operating systems, install the PostgreSQL distribution from the yum repository
.
Connecting from graphical IDEs
Connections were tested in the following environment:
- Ubuntu 20.04, DBeaver:
22.2.4 - MacOS Monterey 12.7:
- JetBrains DataGrip:
2023.3.4 - DBeaver Community:
24.0.0
- JetBrains DataGrip:
From graphical IDEs, you can only connect to public cluster hosts using an SSL certificate.
To avoid connection errors, save the certificate
- Create a data source:
- Select File → New → Data Source → PostgreSQL.
- Specify the connection settings on the General tab:
-
User, Password: Database user name and password.
-
URL: Connection string:
jdbc:postgresql://<special_FQDN>:6432/<DB_name>You can also use a list of all cluster host FQDNs in the connection string:
jdbc:postgresql://<PostgreSQL_host_1>:6432,...,<PostgreSQL_host_N>:6432/<DB_name> -
Click Download to download the connection driver.
-
- On the SSH/SSL tab:
- Enable Use SSL.
- In the CA file field, specify the path to the SSL certificate for your connection.
- Click Test Connection. If the connection is successful, you will see the connection status and information about the DBMS and driver.
- Click OK to save the data source.
- Create a new database connection:
- In the Database menu, select New connection.
- Select PostgreSQL from the database list.
- Click Next.
- Specify the connection settings on the Main tab:
- Host: Master FQDN or regular host FQDN.
- Port:
6432. - Database: Target database name.
- Under Authentication, specify the database user name and password.
- On the SSL tab:
- Enable Use SSL.
- In the Root certificate field, specify the path to the saved SSL certificate file.
- Click Test Connection .... If the connection is successful, you will see the connection status and information about the DBMS and driver.
- Click Done to save the database connection settings.
Connecting with IAM authentication
You can connect to a PostgreSQL database via the Yandex Cloud CLI using IAM authentication. This method is available to Yandex accounts, federated accounts, and local users. When connecting with IAM authentication, you do not need to obtain an SSL certificate or specify the cluster hosts’ FQDNs.
Before connecting, install the PostgreSQL client:
sudo apt update && sudo apt install --yes postgresql-client
Set up your PostgreSQL cluster for connection:
- Navigate to the Managed Service for PostgreSQL service.
- Click the name of your cluster.
- Enable public access for the cluster hosts:
- Select the Hosts tab.
- Click
in the first host's row and select Edit. - Enable Public access.
- Repeat the same for the remaining hosts in the cluster.
- Assign the following role to the service account of the user that will connect to the database:
- Select the Access bindings tab and click Assign roles.
- Enter the user's email the service account is associated with.
- Click
Add role and select themanaged-postgresql.clusters.connectorrole. - Click Save.
- Create a user named PostgreSQL:
- Select the Users tab.
- Click Create user.
- Select IAM as the authentication method.
- Select the account with the
managed-postgresql.clusters.connectorrole. - In the Database field, click
. - Select the database from the drop-down list.
- Click Save.
To connect to the PostgreSQL database, run this command:
yc managed-postgresql connect <cluster_name_or_ID> --db <DB_name>
Connecting from Yandex WebSQL
You can use Yandex WebSQL to send SQL queries to Managed Service for PostgreSQL cluster databases.
WebSQL is a Yandex Cloud service that enables you to connect to managed database clusters, work with databases, tables, and schemas, and run queries. It is a web-based tool that requires no additional authorization and simplifies working with SQL commands by prompting the user.
To connect from WebSQL, activate the WebSQL access option in the cluster settings. You can enable it when creating or updating a cluster.
In the Managed Service for PostgreSQL cluster, a Connection Manager connection is automatically created for each database user, which you can use to connect to the database from WebSQL. If required, you can also create a new connection.
To connect to the database from WebSQL:
-
In the management console
, select the folder with the cluster you need. -
Go to Managed Service for PostgreSQL.
-
Click the cluster name and go to the WebSQL tab.
-
Select the required connection.
The connection will open in WebSQL. To go to the query editor, select the required database.
Check this PostgreSQL
reference for supported queries.Note
You cannot use SQL statements to perform operations requiring superuser privileges.
For more information on how to work with WebSQL, see these guides.
Connecting from pgAdmin 4
Connection testing was performed for pgAdmin 4
Connections from pgAdmin 4 are only permitted to publicly accessible cluster hosts and require an SSL certificate.
Create a new server connection:
-
Select Object → Register → Server...
-
On the General tab, in the Name field, specify the cluster name to be shown in the pgAdmin 4 interface. You can set any name.
-
In the Connection tab, specify the connection settings:
- Host name/address: Master FQDN or regular host FQDN.
- Port:
6432. - Maintenance database: Target database name.
- Username: Username used to establish the connection.
- Password: User password.
-
In the Parameters tab:
- Set the SSL mode parameter to
verify-full. - Add a new Root certificate parameter and specify the path to the saved SSL certificate file in it.
- Set the SSL mode parameter to
-
Click Save to save the server connection settings.
Your cluster will appear in the server list located in the navigation menu.
Connecting from Looker Studio
Connections from Looker Studio
-
Save the
CA.pemserver certificate to a local directory. -
In the same directory, generate a client certificate with a private key:
openssl req -newkey rsa:2048 -nodes -keyout private.pem -out cert.pemDuring certificate creation, the program will ask you to modify several settings. Press Enter to keep the default values.
You will see two files in your local directory:
cert.pemandprivate.pem. -
On the Looker Studio navigation page
, select Create → Data source. -
Select PostgreSQL.
-
Fill out the fields as follows:
- Host name or IP address: Master FQDN or regular host FQDN.
- Port:
6432. - Database: DB to connect to.
- Username: Username used to establish the connection.
- Password: User password.
-
Check Enable SSL and Enable client authentication.
-
Specify the certificate files and the client private key in the appropriate fields:
- Server certificate: Select the
CA.pemfile. - Client certificate: Select the
cert.pemfile. - Client private key: Select the
private.pemfile.
- Server certificate: Select the
-
Click Authenticate.
Before you connect from a Docker container
To connect to a Managed Service for PostgreSQL cluster from a Docker container, add the following lines to the Dockerfile:
RUN apt-get update && \
apt-get install postgresql-client --yes
See the Yandex Serverless Containers connection example in this tutorial.
RUN apt-get update && \
apt-get install wget postgresql-client --yes && \
mkdir --parents ~/.postgresql && \
wget "https://storage.yandexcloud.net/cloud-certs/CA.pem" \
--output-document ~/.postgresql/root.crt && \
chmod 0655 ~/.postgresql/root.crt
Examples of connection strings
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.
Bash
Before connecting, install the required dependencies:
sudo apt update && sudo apt install --yes postgresql-client
-
Connect to a database:
psql "host=c-<cluster_ID>.rw.mdb.yandexcloud.net \ port=6432 \ sslmode=disable \ dbname=<DB_name> \ user=<username> \ target_session_attrs=read-write"Once you run this command, enter the user password to establish the connection.
-
To check the connection, run the following query:
SELECT version();
-
Connect to a database:
psql "host=c-<cluster_ID>.rw.mdb.yandexcloud.net \ port=6432 \ sslmode=verify-full \ dbname=<DB_name> \ user=<username> \ target_session_attrs=read-write"Once you run this command, enter the user password to establish the connection.
-
To check the connection, run the following query:
SELECT version();
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 Maven configuration file:
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>Latest Maven dependency version: 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 postgresqlAfter connecting 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 postgresqlAfter connecting 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
PowerShell
Before connecting, install PostgreSQL for Windows
-
Set the environment variables for the connection:
$Env:PGSSLMODE="disable"; $Env:PGTARGETSESSIONATTRS="read-write" -
Connect to a database:
& "C:\Program Files\PostgreSQL\<version>\bin\psql.exe" ` --host=c-<cluster_ID>.rw.mdb.yandexcloud.net ` --port=6432 ` --username=<username> ` <DB_name>Once you run this command, enter the user password to establish the connection.
-
To check the connection, run the following query:
SELECT version();
-
Set the environment variables for the connection:
$Env:PGSSLMODE="verify-full"; $Env:PGTARGETSESSIONATTRS="read-write" -
Connect to a database:
& "C:\Program Files\PostgreSQL\<version>\bin\psql.exe" ` --host=c-<cluster_ID>.rw.mdb.yandexcloud.net ` --port=6432 ` --username<username> ` <DB_name>Once you run this command, enter the user password to establish the connection.
-
To check the connection, run the following query:
SELECT version();
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.