Connect to a database

Updated at:

This topic describes how to connect to a PolarDB for PostgreSQL cluster.

Preparations

Before you connect to a database cluster, complete the following preparations:

  • Obtain the database endpoint and port

    Centralized PolarDB for PostgreSQL cluster

    A centralized PolarDB for PostgreSQL cluster is a cluster whose Edition is Enterprise Edition or Standard Edition.

    Go to the PolarDB console. In Clusters, click the target cluster ID to open its cluster details page. In Database Connections, obtain the database endpoint.

    Note
    • (Recommended) Use the Cluster Endpoint. The default port is 5432.

    • Based on your access environment, select Private or Public.

      • If you use an ECS instance to access PolarDB and the ECS instance and PolarDB are in the same VPC, select Private.

      • If you access PolarDB from an on-premises environment, select Public. To obtain a public endpoint, click Apply on the right.

    • Public means the Internet. Access through a Public endpoint does not provide the best performance for a PolarDB cluster.

    • Virtual hosts and lightweight application servers cannot use a Private endpoint to connect to a PolarDB cluster.

    PolarDB for PostgreSQL Distributed Edition cluster

    Go to the PolarDB console. In Clusters, click the target cluster ID to open its cluster details page. In Database Connections, obtain the database endpoint.

    Note
    • PolarDB for PostgreSQL Distributed Edition clusters include only a Primary Endpoint by default. The default port is 5432.

    • Based on your access environment, select a Private Endpoint or a Public Endpoint.

      • If you use an ECS instance to access PolarDB and the ECS instance and PolarDB are in the same VPC, select a Private Endpoint.

      • If you access PolarDB from an on-premises environment, select a Public Endpoint. To obtain a public endpoint, click Apply.

    • Public Endpoint means the Internet. Access through a Public Endpoint does not provide the best performance for a PolarDB cluster.

    • Virtual hosts and lightweight application servers cannot use a Private Endpoint to connect to a PolarDB cluster.

  • Create a database account

    Go to the PolarDB console. In Clusters, click the target cluster ID to open its cluster details page. In Settings and Management > Accounts, Create a database account.

    Note

    Database accounts can be Privileged Account or Standard Account. Their permissions differ. Create the required database account based on your business requirements.

  • Configure cluster whitelists

    Go to the PolarDB console. In Clusters, click the target cluster ID to open its cluster details page. In Settings and Management > Cluster Whitelists, add an IP whitelist or a security group.

    Note
    • If you use an ECS instance to access PolarDB and the ECS instance and PolarDB are in the same VPC, add the private IP address of the ECS instance to a new IP whitelist group, or add the security group of the ECS instance to the cluster whitelist.

    • If you use an ECS instance to access PolarDB but the ECS instance and PolarDB are not in the same VPC, add the public IP address of the ECS instance to a new IP whitelist group, or add the security group of the ECS instance to the cluster whitelist.

    • If you access PolarDB from an on-premises environment, add the public IP address of your on-premises environment to a new IP whitelist group.

      Obtain the public IP address of your on-premises environment as follows. On Linux, open a terminal, enter curl ifconfig.me, and then press Enter.

      • On Windows, open Command Prompt, enter curl ip.me, and then press Enter.

      • On macOS, open a terminal, enter curl ifconfig.me, and then press Enter.

      If your on-premises network uses a proxy, these methods may not return your actual public IP address. Add the IP address range 0.0.0.0/0 to the whitelist of the PolarDB cluster. After you connect to the cluster, run SELECT pid,usename,datname,client_addr,state,query FROM pg_stat_activity WHERE state = 'active'; to obtain the actual public IP address, add it to the cluster whitelist, and then remove the IP address range 0.0.0.0/0.

    • The IP address range 0.0.0.0/0 allows all sources to access the cluster. Adding it to a cluster whitelist poses significant risks. Do not add it to the whitelist unless necessary.

After you complete the preparations, you can connect to the database cluster.

Connect to a database cluster

You can connect to a database cluster in many ways. Choose the connection method that suits your business requirements. The following are some examples of how to connect to a database cluster:

Use DMS to connect to a cluster

DMS is a graphical data management tool provided by Alibaba Cloud. It is a data management service that integrates data management, schema management, user authorization, security auditing, data trends, data tracking, BI charts, performance optimization, and server management. You can manage your PolarDB cluster directly in DMS without using other tools.

  1. Go to the PolarDB console. In Clusters, click the target cluster ID to open the cluster details page. In the upper-right corner of the page, click Log on to Database.

  2. In the dialog box that appears, enter the Database Account and Database Password that you created for the cluster, and then click Login.

  3. After you log on, in the left-side navigation pane, choose Database Instances > Instances Connected. The PolarDB cluster that you logged on to appears in the list, where you can manage it.

Use a client to connect to a cluster

You can use any general-purpose client to connect to a PolarDB cluster. This example uses pgAdmin 4 v9.0. The procedure is similar for other clients.

  1. Download and install the pgAdmin 4 client.

  2. Open the pgAdmin 4 client, right-click Servers, and choose .

  3. On the General tab, set the connection name. On the Connection tab, configure the information of the cluster to connect to, and click Save.

    Parameter

    Description

    Host name/address

    PolarDB cluster's database endpoint and port.

    • If you use an ECS instance to access the PolarDB cluster and the ECS instance is in the same VPC as the PolarDB cluster, specify the Private endpoint and port.

    • If you access the PolarDB cluster from an on-premises environment, specify the Public endpoint and port.

    • The default port is 5432.

    Port

    Username

    PolarDB cluster's database account and password.

    Password

  4. View the connection result. If the connection information is correct, the following page appears, indicating that the connection is successful.image

    Note

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

Use the command line to connect to a cluster

You can download psql from the PostgreSQL website and use it to connect to a PolarDB database cluster. You can also use the PolarDB-provided PolarDB-Toolspsql tool in the toolkit to connect to a PolarDB database cluster.

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

  • For more information about how to use psql, see the PostgreSQL psql documentation.

Syntax

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

Parameter

Description

host

PolarDB cluster's database endpoint and port.

  • If you use an ECS instance to access the PolarDB cluster and the ECS instance is in the same VPC as the PolarDB cluster, specify the Private endpoint and port.

  • If you access the PolarDB cluster from an on-premises environment, specify the Public endpoint and port.

  • The default port is 5432.

port

username

PolarDB cluster's database account.

dbname

The database that you want to manage.

Example

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

Use an application to connect to a cluster

You connect to a PolarDB for PostgreSQL cluster the same way you connect to other PostgreSQL databases. You only need to replace the database endpoint, port, account, and password. The following examples show how applications in several programming languages access a PolarDB database:

Java

This example uses a Maven project and the PostgreSQL JDBC driver to connect to a PolarDB for PostgreSQL cluster.

  1. First, add the PostgreSQL JDBC driver dependency to the 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> 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 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();
                
                // Run 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

This example uses Python 3 and the psycopg2 library to connect to a PolarDB for PostgreSQL cluster.

  1. First, install the psycopg2 library. If you have not installed it, run the following command:

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

    import psycopg2
    
    try:
        # Connection parameters
        conn = psycopg2.connect(
            host="<HOST>",  # The database host address
            database="<DATABASE>",  # The database name
            user="<USER>",  # The username
            password="<PASSWORD>",  # The password
            port="<PORT>"  # The port
        )
    
        # Create a cursor object
        cursor = conn.cursor()
    
        # Run a query
        cursor.execute("SELECT * FROM <YOUR_TABLE_NAME>")
    
        # Retrieve 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

This example uses Go 1.23.0 with the database/sql package and the lib/pq driver to connect to a PolarDB for PostgreSQL cluster.

  1. First, install the lib/pq driver. Run the following command to install it:

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

    package main
    
    import (
        "database/sql"
        "fmt"
        "log"
    
        _ "github.com/lib/pq" // Initialize the driver
    )
    
    func main() {
        // 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 before the program exits
    
        // Test the connection
        err = db.Ping()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("Connected to PostgreSQL!")
    
        // Query execution example
        rows, err := db.Query("SELECT * FROM <YOUR_TABLE_NAME>")
        if err != nil {
            log.Fatal(err)
        }
        defer rows.Close()
    }
    

Use Power BI Desktop to connect to a cluster

You can use the PostgreSQL connector of Power BI Desktop to connect to a PolarDB for PostgreSQL cluster and load tables.

Before you begin, make sure that the following requirements are met:

  • Download and install Power BI Desktop on a Windows device.

  • You have obtained the database endpoint and port of the cluster, and created a business database and a database account that has access permissions on it.

  • The public egress IP address of the client has been added to the Cluster Whitelists. If the client and the cluster are in the same VPC, use the Private endpoint. If you access the cluster from an on-premises environment, use the Public endpoint.

Procedure

  1. Open Power BI Desktop. On the Home tab, click Get Data > More....

  2. In the Get Data dialog box, choose Database > PostgreSQL database, and click Connect.

  3. In the PostgreSQL database dialog box, configure the following parameters, set Data Connectivity mode to Import, and click OK.

    Parameter

    Description

    Server

    Enter the database endpoint and port of the cluster in the format endpoint:port, for example, pc-xxxxxx.pg.polardb.rds.aliyuncs.com:5432. Do not add the postgresql:// or jdbc: prefix. Use the port displayed in the console.

    Database

    Enter the name of the business database to connect to. Do not use the default system database postgres for business operations.

  4. In the Authentication dialog box, select Database as the authentication type, enter the User name and Password of the database account, and click Connect. The PostgreSQL connector of Power BI uses database authentication and does not support Windows integrated authentication.

    Note

    If the Encryption Support dialog box appears and SSL is not enabled for the cluster, click OK to continue connecting without encryption.

  5. After the connection succeeds, select the tables to import in the Navigator. Click Load to import the data directly, or click Transform Data to clean the data in Power Query.

FAQ

An ECS instance cannot connect to a PolarDB cluster

Troubleshoot the issue as follows:

  1. Check whether the PolarDB cluster is Running.

  2. Check the database endpoint, port, account, and password. For more information, see Obtain the database endpoint and port.

  3. Check the network. On the ECS instance, run ping database endpoint or telnet database endpoint port to test network connectivity.

    1. If you use a Private endpoint:

      1. Check whether the ECS instance and the PolarDB cluster are in the same VPC. If not, you cannot use a Private endpoint. You can use either of the following methods to place the ECS instance and the PolarDB cluster in the same VPC:

      2. Check whether the private IP address, CIDR block, or security group of the ECS instance has been added to the cluster whitelist.

    2. If you use a Public endpoint, check whether the public IP address or security group of the ECS instance has been added to the cluster whitelist.

Note

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

An on-premises environment cannot connect to a PolarDB cluster

Troubleshoot the issue as follows:

  1. Check whether the PolarDB cluster is Running.

  2. Check the database endpoint, port, account, and password. For more information, see Obtain the database endpoint and port.

    Note

    The database endpoint must be a Public endpoint. If you use an ECS instance in the same VPC as the PolarDB cluster, you can use a Private endpoint.

  3. Check the network. In the on-premises environment, run ping <database endpoint> or telnet <database endpoint> <port> to test network connectivity.

  4. Check whether the public IP address or CIDR block of the on-premises environment has been added to the cluster whitelist.

    Obtain the public IP address of your on-premises environment as follows. On Linux, open a terminal, enter curl ifconfig.me, and then press Enter.

    • On Windows, open Command Prompt, enter curl ip.me, and then press Enter.

    • On macOS, open a terminal, enter curl ifconfig.me, and then press Enter.

    If your on-premises network uses a proxy, these methods may not return your actual public IP address. Add the IP address range 0.0.0.0/0 to the whitelist of the PolarDB cluster. After you connect to the cluster, run SELECT pid,usename,datname,client_addr,state,query FROM pg_stat_activity WHERE state = 'active'; to obtain the actual public IP address, add it to the cluster whitelist, and then remove the IP address range 0.0.0.0/0.

Cannot connect to a PolarDB cluster. Error: Password authentication failed for user

The database account or password is incorrect. Verify your input. Go to the PolarDB console, and in Settings and Management > Accounts, manage database accounts and passwords.

Cannot connect to a PolarDB cluster. Error: Name or service not known

The database endpoint is incorrect. Verify the input. The correct format is pc-xxx.xxx.rds.aliyuncs.com. Go to the PolarDB console, and in Basic Information > Database Connections, manage your database endpoint.

Cannot connect to a PolarDB cluster. Error: Connection timed out

The public IP address or CIDR block of your current environment might not have been added to the whitelist of the PolarDB cluster, or the public IP address or CIDR block that you entered might be incorrect.

Obtain the public IP address of your on-premises environment as follows. On Linux, open a terminal, enter curl ifconfig.me, and then press Enter.

  • On Windows, open Command Prompt, enter curl ip.me, and then press Enter.

  • On macOS, open a terminal, enter curl ifconfig.me, and then press Enter.

If your on-premises network uses a proxy, these methods may not return your actual public IP address. Add the IP address range 0.0.0.0/0 to the whitelist of the PolarDB cluster. After you connect to the cluster, run SELECT pid,usename,datname,client_addr,state,query FROM pg_stat_activity WHERE state = 'active'; to obtain the actual public IP address, add it to the cluster whitelist, and then remove the IP address range 0.0.0.0/0.

How do I change the connection method in DMS to use a Cluster Endpoint to connect to a PolarDB cluster?

When you use DMS to connect to a cluster, by default DMS uses the Primary Endpoint to connect to the cluster. If your business needs require you to change the connection method to use the Cluster Endpoint to connect to the PolarDB cluster, perform the following steps.

  1. After you connect to the cluster in DMS, in the Database Instances > Instances Connected list in the left-side navigation pane, select the target cluster, right-click it, and select Edit Instance.

  2. In the Edit Instance dialog box, change Basic Information > Connection Method to Connection String Address, and enter the cluster's Cluster Endpoint. Click Save.

Important

Because the original SQL window uses the Primary Endpoint to connect to the cluster, after you change the Connection String Address, close the original SQL window and open a new SQL window to run SQL statements.

References