All Products
Search
Document Center

PolarDB:Database connection

Last Updated:Apr 24, 2025

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

Preparations

Perform the following operations before you connect to a cluster:

  • Obtain the database endpoint and port

    Log on to the PolarDB console. Click Clusters in the left-side navigation pane. Select a region in the upper-left corner and click the ID of the cluster in the list to go to the Basic Information page. Obtain the endpoint in the Database Connections section. image

    Note
    • We recommend that you use the Cluster Endpoint. The default port number is 3306.

    • Use the Private or Public endpoint based on your access environment.

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

      • If you want to access the PolarDB cluster from your local environment, use the Public endpoint. Click Apply to the right of the Public endpoint to apply for a public endpoint.

    • A PolarDB cluster cannot achieve optimal performance when it is connected by using a public endpoint.

    • Virtual hosts and lightweight servers cannot be used to connect to a PolarDB cluster by using a Private endpoint.

  • Create a database account

    Log on to the PolarDB console. Click Clusters in the left-side navigation pane. Select a region in the upper-left corner and click the ID of the cluster in the list to go to the Basic Information page. Choose Settings and Management > Accounts to create a database account. image

    Note
    • You can create a Privileged Account or a Standard Account. These two types of accounts have different permissions. Create a database account based on your business requirements.

  • Configure an IP whitelist

    Log on to the PolarDB console. Click Clusters in the left-side navigation pane. Select a region in the upper-left corner and click the ID of the cluster in the list to go to the Basic Information page. Choose Settings and Management > Cluster Whitelists to add an IP address whitelist or a security group.

    image

    Note
    • If you want to access the PolarDB cluster from an ECS instance and the ECS instance is in the same VPC as the PolarDB cluster, add the private IP addresses of ECS instances to an IP address whitelist, or add the security group to which the ECS instance belongs to the cluster whitelist.

    • If you want to access the PolarDB cluster from an ECS instance and the ECS instance is in a different VPC from the PolarDB cluster, you can add the public IP address of the ECS instance to a new IP address whitelist or add the security group to which the ECS instance belongs to the cluster whitelist.

    • If you want to access the PolarDB cluster from your local environment, add the public IP address of your local environment to a new IP address whitelist.

      Use the following methods to obtain the public IP address of your local environment:

      • Linux: Open the CLI, enter the curl ifconfig.me command, and then press the Enter key.

      • Windows: Open Command Prompt, enter the curl ip.me command, and then press the Enter key.

      • macOS: Start Terminal, enter the curl ifconfig.me command, and then press the Enter key.

      If a proxy is used for your local network environment, the IP address obtained by the preceding method may not be your actual public IP address. You can add the 0.0.0.0/0 CIDR block to the whitelist of the PolarDB cluster. After you connect to the cluster, run the SHOW PROCESSLIST; command to obtain the public IP address and add it to the whitelist of the cluster. Then, delete the 0.0.0.0/0 CIDR block from the whitelist.

      image

    • 0.0.0.0/0 in the IP whitelist indicates that all sources are allowed to access the cluster. Do not add 0.0.0.0/0 to the IP whitelist of the cluster unless it is necessary.

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

Connect to a cluster.

You can select a connection method based on your business requirements. See the following examples of connecting to a cluster:

Use DMS to connect to a cluster

DMS is a visualized data management service provided by Alibaba Cloud. DMS provides various management services such as data management, schema management, access control, security audit, business intelligence (BI) charts, data trends, data tracking, performance optimization, and server management. You can manage your PolarDB clusters in DMS without the need to use other tools.

  1. Log on to the PolarDB console. Click Clusters in the left-side navigation pane. Select a region in the upper-left corner and click the ID of the cluster in the list to go to the Basic Information page. In the upper-right corner of the page, click Log on to Database. image

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

  3. After you log on to the PolarDB for MySQL cluster, click Instances Connected in the left-side navigation pane to view and manage the PolarDB for MySQL cluster. image

Use a client to connect to a cluster

You can use a MySQL client to connect to a PolarDB cluster. MySQL Workbench 8.0.29 is used in this example. The operations by using other types of clients are similar.

  1. Install MySQL Workbench. For more information, visit the MySQL Workbench download page.

  2. Start MySQL Workbench and choose Database > Connect to Database.

  3. Enter the connection information and click OK.

    连接界面

    Parameter

    Description

    Example

    Hostname

    The database endpoint. For more information, see Database connection.

    pc-2***.rwlb.rds.aliyuncs.com

    Port

    The port number that corresponds to the database endpoint.

    Note

    The default port number is 3306.

    3306

    Username

    The database account. For more information, see Create a database account.

    polardb_mysql_user

    Password

    The password of the database account.

    Pass***233

Use the CLI to connect to a cluster

If MySQL client is installed on your server, you can run commands in the CLI to connect to a PolarDB for MySQL cluster.

Syntax:

mysql -h <Endpoint> -P <Port> -u <Account> -p <Password>

Example:

mysql -h pc-2***.rwlb.rds.aliyuncs.com -P3306 -upolardb_mysql_user -pPass***233

Parameter

Description

Example

-h

The database endpoint. For more information, see Database connection.

pc-2***.rwlb.rds.aliyuncs.com

-P

The port number that corresponds to the database endpoint.

Note
  • The default port number is 3306.

  • If you want to use the default port, you do not need to specify a value for this parameter.

3306

-u

The database account. For more information, see Create a database account.

polardb_mysql_user

-p

The password of the database account.

Note

This parameter is required.

  • If you do not specify this parameter, you are required to enter the password again when the Enter password message is displayed.

  • If you specify this parameter, do not enter space characters between -p and the password.

Pass***233

Use an application to connect to a cluster

Connecting to a PolarDB for MySQL cluster is similar to connecting to regular MySQL databases. You only need to replace the endpoint, port, account, and password of the database. The following examples show how to use applications to access a PolarDB database in some development languages:

Java

In this example, a Maven project is used to connect to the PolarDB for MySQL cluster by using the MySQL JDBC driver.

  1. First, add the dependency of the MySQL JDBC driver to the pom.xml file. Sample code:

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.27</version>
    </dependency>
  2. Connect to the cluster. Replace the <HOST>, port number, <USER>, <PASSWORD>, <DATABASE>, <YOUR_TABLE_NAME>, and <YOUR_TABLE_COLUMN_NAME> with the information of your database.

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class DatabaseConnection {
       public DatabaseConnection() {
       }
    
       public static void main(String[] args) {
          // The endpoint, port, and database name of the PolarDB cluster to be connected.
          String url = "jdbc:mysql://<HOST>:3306/<DATABASE>?useSSL=false&serverTimezone=UTC";
          // The database account.
          String user = "<USER>";
          // The password of the database account.
          String password = "<PASSWORD>";
    
          try {
             Class.forName("com.mysql.cj.jdbc.Driver");
             Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement();
             // The name of the data table to be queried.
             ResultSet rs = stmt.executeQuery("SELECT * FROM `<YOUR_TABLE_NAME>`");
    
             while(rs.next()) {
                // The column name of the data table to be queried.
                System.out.println(rs.getString("<YOUR_TABLE_COLUMN_NAME>"));
             }
    
             rs.close();
             stmt.close();
             conn.close();
          } catch (Exception var7) {
             var7.printStackTrace();
          }
    
       }
    }

Python

In this example, Python3 is used to connect to the PolarDB for MySQL cluster by using the PyMySQL library.

  1. First, install the PyMySQL library. You can run the following command to install it:

    pip3 install PyMySQL
  2. Connect to the cluster. Replace the <HOST>, port number, <USER>, <PASSWORD>, <DATABASE>, and <YOUR_TABLE_NAME> with the information of your database.

    import pymysql
    
    # The database connection parameters.
    host = '<HOST>' # The endpoint of the PolarDB cluster.
    port = 3306 # The default port 3306
    user = '<USER>' # The database account.
    password = '<PASSWORD>' # The password of the database account.
    database = '<DATABASE>' # The name of the database to be connected.
    
    try:
        # Establish a database connection.
        connection = pymysql.connect(
            host=host,
            port=port,
            user=user,
            passwd=password,
            db=database
        )
    
        # Obtain the cursor.
        with connection.cursor() as cursor:
            # Execute an SQL query.
            sql = "SELECT * FROM '<YOUR_TABLE_NAME>'" # The name of the table to be queried.
            cursor.execute(sql)
    
            # Obtain the query result.
            results = cursor.fetchall()
            for row in results:
                print(row)
    
    finally:
        # Close the database connection.
        if 'connection' in locals() and connection.open:
            connection.close()
    

Go

In this example, go1.23.0 is used to connect to the PolarDB for MySQL cluster by using the database/sql package and go-sql-driver/mysql driver.

  1. First, install the go-sql-driver/mysql driver. You can run the following command to install the driver:

    go get -u github.com/go-sql-driver/mysql
  2. Connect to the cluster. Replace the <HOST>, port number, <USER>, <PASSWORD>, <DATABASE>, and <YOUR_TABLE_NAME> with the information of your database.

    package main
    
    import (
        "database/sql"
        "fmt"
        "log"
        _ "github.com/go-sql-driver/mysql"
    )
    
    func main() {
        // Database connection parameters.
        dbHost := "<HOST>" // The endpoint of the PolarDB cluster.
        dbPort := "3306" // The default port 3306.
        dbUser := "<USER>" // The database account.
        dbPass := "<PASSWORD>" // The password of the database account.
        dbName := "<DATABASE>" // The name of the database to be connected.
    
        // Build DSN (Data Source Name)
        dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", dbUser, dbPass, dbHost, dbPort, dbName)
    
        // Create a database connection.
        db, err := sql.Open("mysql", dsn)
        if err != nil {
            log.Fatalf("Failed to connect to database: %v", err)
        }
        defer db.Close()
    
        // Test the connection.
        err = db.Ping()
        if err != nil {
            log.Fatalf("Failed to ping database: %v", err)
        }
    
        // Create a cursor.
        var result string
        err = db.QueryRow("SELECT VERSION()").Scan(&result)
        if err != nil {
            log.Fatalf("Failed to execute query: %v", err)
        }
    
        // Print the database version.
        fmt.Printf("Connected to database, version: %s\n", result)
    
        // Execute an SQL query.
        rows, err := db.Query("SELECT * FROM '<YOUR_TABLE_NAME>'") // The name of the data table that is queried.
        if err != nil {
            log.Fatalf("Failed to execute query: %v", err)
        }
        defer rows.Close()

FAQ

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

Use the following steps to troubleshoot the issue:

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

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

  3. Check the network conditions. You can run ping or telnet commands in the ECS instance to test the network connectivity.

  4. If you are using a Private endpoint:

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

    2. Check whether the private IP address, CIDR block, or security group of the ECS instance is added to the whitelist of the PolarDB cluster. For more information, see Configure a whitelist.

  5. If you are using a Public endpoint, check whether the public IP address or security group of the ECS instance is added to the whitelist of the PolarDB cluster. For more information, see Configure a whitelist.

Note

Virtual hosts and lightweight servers cannot be used to connect to a PolarDB cluster by using a Private endpoint.

Why am I unable to connect to the PolarDB cluster from my local environment?

Use the following steps to troubleshoot the issue:

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

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

    Note

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

  3. Check the network conditions. You can run ping or telnet commands in your local environment to test the network connectivity.

  4. Check whether the public IP address or CIDR block of your local environment is added to the whitelist of the PolarDB cluster. For more information, see Configure a whitelist.

    Use the following methods to obtain the public IP address of your local environment:

    • Linux: Open the CLI, enter the curl ifconfig.me command, and then press the Enter key.

    • Windows: Open Command Prompt, enter the curl ip.me command, and then press the Enter key.

    • macOS: Start Terminal, enter the curl ifconfig.me command, and then press the Enter key.

    If a proxy is used for your local network environment, the IP address obtained by the preceding method may not be your actual public IP address. You can add the 0.0.0.0/0 CIDR block to the whitelist of the PolarDB cluster. After you connect to the cluster, run the SHOW PROCESSLIST; command to obtain the public IP address and add it to the whitelist of the cluster. Then, delete the 0.0.0.0/0 CIDR block from the whitelist.

    image

I cannot connect to the PolarDB cluster. The following error is returned: Access denied for user 'xxx'@'xxx' (using password: YES)

The database account or password is incorrect. Make sure you enter the correct account and password. You can 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: Unknown MySQL server host 'xxx'

The database endpoint is incorrect. Make sure you enter the correct endpoint. The endpoint format is pc-xxxxxx.rwlb.rds.aliyuncs.com. You can log on to the PolarDB console and choose Basic Information > Database Connections to manage the endpoints of your database.

I cannot connect to the PolarDB cluster. The following error is returned: Can't connect to MySQL server on 'xxx'or Connection timed out

It is possible that the public IP address or CIDR block of the current environment is not added to the whitelist of the PolarDB cluster, or the public IP address or CIDR block added to the whitelist is incorrect.

Use the following methods to obtain the public IP address of your local environment:

  • Linux: Open the CLI, enter the curl ifconfig.me command, and then press the Enter key.

  • Windows: Open Command Prompt, enter the curl ip.me command, and then press the Enter key.

  • macOS: Start Terminal, enter the curl ifconfig.me command, and then press the Enter key.

If a proxy is used for your local network environment, the IP address obtained by the preceding method may not be your actual public IP address. You can add the 0.0.0.0/0 CIDR block to the whitelist of the PolarDB cluster. After you connect to the cluster, run the SHOW PROCESSLIST; command to obtain the public IP address and add it to the whitelist of the cluster. Then, delete the 0.0.0.0/0 CIDR block from the whitelist.

image

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

By default, Data Management (DMS) uses the primary endpoint to connect to a PolarDB cluster. However, to use specific features of the cluster, such as IMCIs and PolarDB for AI, you must use the cluster endpoint to connect to the cluster to ensure that PolarProxy can correctly route SQL queries to the appropriate nodes.

To change the connection method for a PolarDB cluster in DMS from the primary endpoint to the cluster endpoint, follow these steps:

  1. Access DMS and connect to the PolarDB cluster. In the left-side navigation pane of DMS, choose Database Instances > Instances Connected and find the cluster. 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