All Products
Search
Document Center

PolarDB:Connect to a global database network

Last Updated:Aug 27, 2026

To connect to the GDN, connect your application to the nearest cluster endpoint based on its region. The GDN automatically performs read/write splitting. Read requests are typically routed to the local cluster, while write requests are forwarded to the primary cluster.

Request routing

Each cluster's database proxy configuration determines request routing. No application changes needed — connect to a cluster endpoint and requests route automatically:

  • Write requests (INSERT, UPDATE, DELETE) and in-transaction requests route to the primary node of the primary cluster.

  • Read requests route to read-only nodes of the local secondary cluster by default. With session consistency enabled, some reads may route to the primary cluster's primary node.

Click to view detailed forwarding logic

Target node

Forwarded requests

Sent only to the primary node of the primary cluster

  • DML operations (such as INSERT, UPDATE, and DELETE)

  • DDL operations (such as creating or deleting tables or databases, or altering table schemas)

  • SHOW commands

  • Transaction-related commands such as BEGIN and COMMIT

  • LISTEN, UNLISTEN, and NOTIFY commands

  • ANALYZE command

  • Two-phase commit protocol commands

  • Requests within a transaction (behavior may vary based on the transaction splitting configuration)

  • Function definitions and calls (behavior may vary based on the user-defined function routing rule configuration)

  • Requests that use temporary tables

  • Multi-statement Multi Statements

  • PREPARE statements that contain write requests

Sent to read-only nodes or the primary node

  • Read requests outside a transaction

  • EXPLAIN command

  • PREPARE statements that contain read requests

Always sent to all nodes

  • USE command

  • DISCARD and DEALLOCATE commands

Note
  • Only cluster endpoints or custom endpoints with the Read-write mode set to Read/Write (Automatic Read/Write Splitting) support GDN read/write splitting.

  • The Primary address and custom endpoints with the Read-write mode set to Read-only do not support GDN read/write splitting.

  • To mitigate the potential impact of replication latency between the primary and secondary clusters on your business, we recommend that when you configure a custom cluster endpoint on a secondary cluster, you set Primary Node Accepts Read Requests to No and set Consistency Level to Eventual Consistency (Weak).

View a cluster endpoint

  1. Log on to the PolarDB console. In the left-side navigation pane, click Global Database Network (GDN).

  2. On the Global Database Network (GDN) page, find the target GDN and click its Global Database Network ID to go to the details page.

  3. In the Clusters section, find the target secondary cluster and click View in the Cluster Endpoint column to view the cluster endpoint details in the dialog box that appears.

    Note
    • You can view the endpoint information only for the default cluster, including the Internal Network and Internet endpoints.

    • To view details of more endpoints, click Visit the Overview page of the cluster. You are redirected to the cluster's details page, where you can find more endpoints in the Database Connections section.

Connect to a GDN cluster

You can connect to a database cluster using various methods. The following sections provide examples:

Use DMS to connect to a cluster

Data Management (DMS) provides database administration, security auditing, and performance optimization. Manage your PolarDB cluster directly in DMS.

  1. Log on to the PolarDB console. In the cluster list, click a cluster ID to open the Basic Information page. In the upper-right corner, click Log On To Database.image

  2. In the dialog box, enter the database account and password, then click Login.image

  3. After you log on, choose Database Instances > Instances Connected in the left-side navigation pane to manage the cluster.image

Use a client to connect to a cluster

This procedure uses pgAdmin 4 v9.0 to connect to a PolarDB cluster.

  1. Download and install the pgAdmin 4 client.

  2. Open the pgAdmin 4 client, right-click Servers, and select Register > Server....image

  3. On the General tab, set the connection name. On the Connection tab, configure the connection parameters, then click Save.image

    image

    Parameter

    Description

    Host name/address

    The endpoint and port of the PolarDB cluster.

    • To access the PolarDB cluster from an ECS instance, and the ECS instance is in the same VPC as the PolarDB cluster, specify the Private endpoint and port.

    • To access the PolarDB cluster from your on-premises environment, specify the Public endpoint and port.

    • The default port number is 5432.

    Port

    Username

    The database account and password of the PolarDB cluster.

    Password

  4. A successful connection displays the following page.image

    Note

    postgres is the default system database. Do not perform any operations on this database.

Use psql to connect to a cluster

Download psql from PostgreSQL Downloads to connect to a PolarDB cluster. You can also use psql in the PolarDB-Tools to connect to a PolarDB cluster.

Note
  • The connection method is the same for Windows and Linux.

  • The official psql documentation covers detailed usage.

Syntax

psql -h <host> -p <port> -U <username> -d <dbname>

Parameter

Description

host

The cluster endpoint and port of the PolarDB cluster.

  • To access the PolarDB cluster from an ECS instance, and the ECS instance is in the same VPC as the PolarDB cluster, specify the Private endpoint and port.

  • To access the PolarDB cluster from your on-premises environment, specify the Public endpoint and port.

  • The default port number is 5432

port

username

The database account of the PolarDB cluster.

dbname

The database name.

Example

psql -h pc-xxx.rwlb.rds.aliyuncs.com -p 5432 -U testusername -d postgres

Connect to a cluster in a programming language

Connecting to a PolarDB for PostgreSQL cluster is similar to connecting to a regular PostgreSQL database — just update the endpoint, port, account, and password.

Java

Connect to a PolarDB for PostgreSQL cluster using the PostgreSQL JDBC driver in a Maven-based Java project.

  1. Add the PostgreSQL JDBC driver dependency to your pom.xml file. Sample code:

    <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <version>42.2.18</version>
    </dependency>
  2. Connect to the cluster. Replace the <HOST>, <PORT>, <USER>, <PASSWORD>, <DATABASE>, <YOUR_TABLE_NAME>, and <YOUR_TABLE_COLUMN_NAME> placeholders with the actual cluster connection parameters.

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class PolarDBConnection {
        public static void main(String[] args) {
            // Database URL, username, and password.
            String url = "jdbc:postgresql://<HOST>:<PORT>/<DATABASE>";
            String user = "<USER>";
            String password = "<PASSWORD>";
    
            try {
                // Load the PostgreSQL JDBC driver.
                Class.forName("org.postgresql.Driver");
                
                // Establish the connection.
                Connection conn = DriverManager.getConnection(url, user, password);
                
                // Create a Statement object.
                Statement stmt = conn.createStatement();
                
                // Execute an SQL query.
                ResultSet rs = stmt.executeQuery("SELECT * FROM <YOUR_TABLE_NAME>");
                
                // Process the result set.
                while (rs.next()) {
                    System.out.println(rs.getString("<YOUR_TABLE_COLUMN_NAME>"));
                }
                
                // Close resources.
                rs.close();
                stmt.close();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

Python

Connect to a PolarDB for PostgreSQL cluster using the psycopg2 library in Python 3.

  1. Install the psycopg2 library.

    pip3 install psycopg2-binary
  2. Connect to the cluster. Replace the <HOST>, <PORT>, <USER>, <PASSWORD>, <DATABASE>, and <YOUR_TABLE_NAME> placeholders with the actual cluster connection parameters.

    import psycopg2
    
    try:
        # Connection parameters
        conn = psycopg2.connect(
            host="<HOST>",  # The cluster endpoint.
            database="<DATABASE>",  # The database name.
            user="<USER>",  # The username.
            password="<PASSWORD>",  # The password.
            port="<PORT>"  # The port number.
        )
    
        # Create a cursor object.
        cursor = conn.cursor()
    
        # Execute a query.
        cursor.execute("SELECT * FROM <YOUR_TABLE_NAME>")
    
        # Get all results.
        records = cursor.fetchall()
        for record in records:
            print(record)
            
    except Exception as e:
        print("Error:", e)
    finally:
        # Close the connection.
        if 'cursor' in locals():
            cursor.close()
        if 'conn' in locals():
            conn.close()

Go

Connect to a PolarDB for PostgreSQL cluster using the database/sql package and the lib/pq driver in Go 1.23.0.

  1. Install the lib/pq driver.

    go get -u github.com/lib/pq
  2. Connect to the cluster. Replace the <HOST>, <PORT>, <USER>, <PASSWORD>, <DATABASE>, and <YOUR_TABLE_NAME> placeholders with the actual cluster connection parameters.

    package main
    
    import (
        "database/sql"
        "fmt"
        "log"
    
        _ "github.com/lib/pq" // Initialize the PostgreSQL driver.
    )
    
    func main() {
        // The connection string format.
        connStr := "user=<USER> password=<PASSWORD> dbname=<DATABASE> host=<HOST> port=<PORT> sslmode=disable"
    
        // Open a database connection.
        db, err := sql.Open("postgres", connStr)
        if err != nil {
            log.Fatal(err)
        }
        defer db.Close() // Close the connection when the program exits.
    
        // Test the connection.
        err = db.Ping()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("Connected to PostgreSQL!")
    
        // Execute a query.
        rows, err := db.Query("SELECT * FROM <YOUR_TABLE_NAME>")
        if err != nil {
            log.Fatal(err)
        }
        defer rows.Close()
    }
    

Related APIs

API

Description

DescribeDBClusterEndpoints

Queries the connection endpoint information of a PolarDB cluster.

ModifyDBClusterEndpoint

Modifies properties of a PolarDB cluster endpoint, such as read/write mode, automatic node addition, consistency level, transaction splitting, whether the primary node accepts read requests, and connection pooling.