All Products
Search
Document Center

PolarDB:Connect to a database

Last Updated:Jun 10, 2026

Connect to a cluster by using DMS, pgAdmin, psql, or a programming language.

Prerequisites

Before you connect:

  • Obtain the cluster endpoint and port

  • Create a database account

    Log on to the PolarDB console. In the cluster list, click a cluster ID to open the Basic Information page. In the left-side navigation pane, choose Settings and Management > Accounts to .image

    Note

    You can create a Privileged Account or a Standard Account. These account types have . Create an account based on your requirements.

  • Configure a cluster whitelist

    Log on to the PolarDB console. In the cluster list, click a cluster ID to open the Basic Information page. In the left-side navigation pane, choose Settings and Management > Cluster Whitelists, add an or a .image

    Note
    • To access the PolarDB cluster from an ECS instance in the same VPC as the PolarDB cluster, add the ECS instance's internal IP address to a whitelist, or add its security group.

    • To access the PolarDB cluster from an ECS instance in a different VPC from the PolarDB cluster, add the ECS instance's public IP address to a whitelist, or add its security group.

    • To access the PolarDB cluster from your on-premises environment, add your public IP address to a whitelist.

      Obtain your public IP address:

      • Linux: Run curl ifconfig.me.

      • Windows: Run curl ip.me in Command Prompt.

      • macOS: Run curl ifconfig.me in Terminal.

      If your network uses a proxy, the preceding method may not return your actual public IP address. Temporarily add the 0.0.0.0/0 CIDR block to a whitelist of the PolarDB cluster. After you connect, run SELECT pid,usename,datname,client_addr,state,query FROM pg_stat_activity WHERE state = 'active'; to find your actual public IP address and add it to the whitelist. Then, remove the 0.0.0.0/0 CIDR block.

      image

    • Adding the 0.0.0.0/0 CIDR block to an IP whitelist allows all sources to access the cluster. Only use this CIDR block when necessary.

You can now connect to the cluster.

Connect to a cluster

Choose a connection method.

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.

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

  3. After you log on, choose Database Instances > Instances Connected in the left-side navigation pane to manage the PolarDB 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

    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 .

    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 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

port

username

The database account of the PolarDB cluster.

dbname

The .

Example

Connect to a cluster in a programming language

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

Java

Connect to a 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 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 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()
    }
    

FAQ

Why am I unable to connect an ECS instance to a PolarDB cluster?

Troubleshoot as follows:

  1. Check whether the PolarDB cluster is in the Running state.

  2. Verify the database endpoint, port, account, and password. Obtain the database endpoint and port.

  3. Test network connectivity from the ECS instance using ping or telnet.

    1. If you are using a Private endpoint:

      1. Verify the ECS instance and the PolarDB cluster are in the same VPC. If not, the Private endpoint is unavailable. Use one of the following methods to connect the ECS instance and PolarDB cluster:

      2. Verify the private IP address, CIDR block, or security group of the ECS instance is in the PolarDB cluster whitelist. Configure a cluster whitelist.

    2. If you are using a Public endpoint, verify the public IP address or security group of the ECS instance is in the PolarDB cluster whitelist. Configure a cluster whitelist.

Note

Virtual hosts and lightweight servers cannot connect to a PolarDB cluster through a Private endpoint.

Why am I unable to connect to the PolarDB cluster from my on-premises environment?

Troubleshoot as follows:

  1. Check whether the PolarDB cluster is in the Running state.

  2. Verify the database endpoint, port, account, and password. Obtain the database endpoint and port.

  3. Note

    A Public endpoint must be used. If you are using an ECS instance that resides in the same VPC as the PolarDB cluster, you can use a Private endpoint.

  4. Test network connectivity from your local environment using ping or telnet.

  5. Verify the public IP address or CIDR block of your local environment is in the PolarDB cluster whitelist. Configure a whitelist

    Obtain your public IP address:

    • Linux: Run curl ifconfig.me.

    • Windows: Run curl ip.me in Command Prompt.

    • macOS: Run curl ifconfig.me in Terminal.

    If your network uses a proxy, the preceding method may not return your actual public IP address. Temporarily add the 0.0.0.0/0 CIDR block to a whitelist of the PolarDB cluster. After you connect, run SELECT pid,usename,datname,client_addr,state,query FROM pg_stat_activity WHERE state = 'active'; to find your actual public IP address and add it to the whitelist. Then, remove the 0.0.0.0/0 CIDR block.

    image

I cannot connect to the PolarDB cluster. The following error is returned: password authentication failed for user

The database account or password is incorrect. Verify your credentials. Log on to the PolarDB console and choose Settings and Management > Accounts to manage the database account and password.

I cannot connect to the PolarDB cluster. The following error is returned: name or service not known

The cluster endpoint is incorrect. The correct format is pc-xxx.xxx.rds.aliyuncs.com. Log on to the PolarDB console and choose Basic Information > Database Connections to manage the endpoints of your cluster.

I cannot connect to the PolarDB cluster. The following error is returned: connection timed out

The public IP address or CIDR block of the current environment is not in the PolarDB cluster whitelist, or the value added is incorrect.

Obtain your public IP address:

  • Linux: Run curl ifconfig.me.

  • Windows: Run curl ip.me in Command Prompt.

  • macOS: Run curl ifconfig.me in Terminal.

If your network uses a proxy, the preceding method may not return your actual public IP address. Temporarily add the 0.0.0.0/0 CIDR block to a whitelist of the PolarDB cluster. After you connect, run SELECT pid,usename,datname,client_addr,state,query FROM pg_stat_activity WHERE state = 'active'; to find your actual public IP address and add it to the whitelist. Then, remove the 0.0.0.0/0 CIDR block.

image

How do I change the connection method for a PolarDB cluster by using DMS from the primary endpoint to the cluster endpoint?

If you use DMS to connect to a cluster, the system uses the Primary Endpoint to connect to the cluster by default. If you must use the Cluster Endpoint to connect to the PolarDB cluster, perform the following steps:

  1. After you connect to the cluster by using DMS, choose Database Instances > Instances Connected in the left-side navigation pane. Find and right-click the cluster and select Edit.

    image

  2. In the Edit dialog box, navigate to the Basic Information section. Change the Connection Method parameter to Connection String Address, enter the cluster endpoint, and then click Save.image

Important

After you change the connection string for accessing a PolarDB cluster, close the original SQL window and open a new one to ensure that the updated settings take effect.

References