All Products
Search
Document Center

PolarDB:Connect to a database

Last Updated:Nov 21, 2025

PolarDB-X supports connections that use Data Management (DMS), the MySQL command line, third-party clients, and third-party application code that is compliant with the official MySQL protocol.

Preparations

Before you connect to a PolarDB-X database, perform the following steps:

  • Obtain the database endpoint and port

    Go to the PolarDB for Distributed console. In the Instances list, click the ID of the target instance to open its Basic Information page. In the Connection Information section, obtain the database endpoint and port.

    image

    Note
    • You can select an Internal Endpoint or a Public Endpoint based on your access environment.

      • If you use ECS to access PolarDB-X, and both ECS and PolarDB-X are in the same VPC, select Internal Endpoint to ensure the best performance of PolarDB-X.

      • If you access PolarDB-X from an on-premises environment, select a Public Endpoint. To obtain a public endpoint, click Apply for Public Endpoint. A Public Endpoint connects to the Internet, but accessing a PolarDB-X instance over the Internet does not provide optimal performance.

    • You cannot use a Internal Endpoint to connect a virtual host or a simple application server to a PolarDB-X instance.

  • Create a database account.

  • Configure a whitelist for the instance

    Go to the PolarDB for Distributed console. In the Instances list, click the ID of the target instance to go to the instance details page. In the navigation pane on the left, choose Configuration Management > Security Management. On the page that appears, Configuration an IP address whitelist or Add Whitelist. For more information, see Configure whitelists.

    image

    Note
    • If your ECS instance and PolarDB-X are in the same VPC, you can add the private IP address of the ECS instance to a new IP whitelist group to access PolarDB-X.

    • If an ECS instance and PolarDB-X are not in the same VPC, you can add the public IP address of the ECS instance to a new IP whitelist group to access PolarDB-X.

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

      To obtain the public IP address of your on-premises machine, use one of the following methods:

      • Linux: Open the terminal and run the curl ifconfig.me command.

      • Windows: Open the command prompt and run the curl ip.me command.

      • macOS: Open the terminal and run the curl ifconfig.me command.

      If your on-premises network uses a proxy, the IP address that you obtain using the preceding methods may not be the actual public IP address. In this case, add the 0.0.0.0/0 CIDR block to the whitelist of the PolarDB-X instance. After you connect to the instance, run the SHOW PROCESSLIST; command to obtain the actual public IP address. Then, add the actual public IP address to the whitelist and remove the 0.0.0.0/0 CIDR block.

      image

    • The 0.0.0.0/0 CIDR block allows access from all sources. This poses significant security threats. Add this CIDR block to a whitelist only when necessary.

Connect to a database

You can use various methods to connect to a database instance. The following sections provide examples of how to connect to a database instance using different methods.

Use DMS to connect to a database

DMS is a graphical data management tool provided by Alibaba Cloud. This integrated data management service provides features such as data management, schema management, user authorization, security audit, data trends, data tracking, BI charts, performance optimization, and server management. You can use DMS to manage your PolarDB-X instance without using other tools.

  1. Go to the PolarDB for Distributed console. In the Instances list, click the ID of the target instance. On the instance details page, click Log On To Database in the upper-right corner.

    image

  2. In the dialog box, enter the Database Account and Database Password for your PolarDB-X instance and click Logon.

    image

    Note
    • By default, the control mode is Flexible Management when you first log on to DMS. You can also modify the control mode after you log on. For more information, see Modify instance information and Control modes.

    • After you configure the logon parameters, click Test Connection in the lower-left corner. If the test connection fails, refer to the error message to check the instance information you entered, such as the account and password.

    • The system automatically adds the DMS server IP addresses to the whitelist of the ApsaraDB database. If the IP addresses are not automatically added, you must add them manually.

  3. After you log on, you can view the PolarDB-X instance in the Instances Connected section of the navigation pane on the left and perform management operations.

    image

Use a client to connect to a database

PolarDB-X supports connections from the following third-party clients. You can download these clients from their official websites.

  • MySQL Workbench (Recommended)

  • SQLyog

  • Sequel Pro

  • Navicat for MySQL

Note

Third-party GUI clients can perform basic database operations, such as creating, retrieving, updating, and deleting data, and DDL operations. PolarDB-X may not support the advanced features of these clients.

The following example uses MySQL Workbench 8.0.29. The steps for other clients are similar.

  1. Install MySQL Workbench. You can download it from the official download page.

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

  3. Enter the connection information and click OK.

    连接界面

    Parameter

    Description

    Example

    Hostname

    The database endpoint.

    pxc-xxx.polarx.rds.aliyuncs.com

    Port

    The port number that corresponds to the database endpoint.

    Note

    The default port is 3306.

    3306

    Username

    The database account.

    polardb_x_user

    Password

    The password of the database account.

    Pass***233

Use the MySQL command line to connect to a database

If a MySQL client is installed on your server, you can run commands to connect to the PolarDB-X instance.

Syntax

mysql -h<endpoint> -P<port> -u<database_username> -p<database_user_password> -D<database_name>

Example

mysql -hpxc-xxx.polarx.rds.aliyuncs.com -P3306 -upolardb_mysql_user -pPass***233 -Dtest_db

Parameter

Description

Example

-h

The database endpoint.

pxc-xxx.polarx.rds.aliyuncs.com

-P

The port number that corresponds to the database endpoint.

Note
  • The default port is 3306.

  • If you use the default port, you can omit this parameter.

3306

-u

The database account.

polardb_x_user

-p

The password of the database account.

Note

This parameter is required.

  • If you do not include this parameter, you are prompted to enter the password after Enter password is returned.

  • If you include this parameter, do not add a space between -p and the password.

Pass***233

-D

The name of the database to which you want to log on.

Note

This parameter is optional.

test_db

Use an application to connect to a database

Connecting to a PolarDB-X instance is similar to connecting to other MySQL databases. You only need to replace the database endpoint, port, account, and password. The following sections describe how to use applications in different programming languages to access a PolarDB database:

Java

This section uses a Maven project as an example to describe how to use a MySQL JDBC driver to connect to a PolarDB-X instance.

  1. Add the dependency for the MySQL JDBC driver to the pom.xml file. The following code provides an example:

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.27</version>
    </dependency>
  2. Connect to the instance. Replace the <HOST>, port number, <USER>, <PASSWORD>, <DATABASE>, <YOUR_TABLE_NAME>, and <YOUR_TABLE_COLUMN_NAME> parameters with your actual values.

    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 name of the database to which you want to connect.
          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 table from which you want to retrieve data.
             ResultSet rs = stmt.executeQuery("SELECT * FROM `<YOUR_TABLE_NAME>`");
    
             while(rs.next()) {
                // The name of the column from which you want to retrieve data.
                System.out.println(rs.getString("<YOUR_TABLE_COLUMN_NAME>"));
             }
    
             rs.close();
             stmt.close();
             conn.close();
          } catch (Exception var7) {
             var7.printStackTrace();
          }
    
       }
    }

Python

This section uses Python 3 as an example to describe how to use the PyMySQL library to connect to a PolarDB-X instance.

  1. Install the PyMySQL library by running the following command:

    pip3 install PyMySQL
  2. Connect to the instance. Replace the <HOST>, port number, <USER>, <PASSWORD>, <DATABASE>, and <YOUR_TABLE_NAME> parameters with your actual values.

    import pymysql
    
    # Database connection parameters.
    host = '<HOST>'  # The endpoint of the PolarDB-X instance.
    port = 3306  # The default port is 3306.
    user = '<USER>'  # The database account.
    password = '<PASSWORD>'  # The password of the database account.
    database = '<DATABASE>'  # The name of the database to which you want to connect.
    
    try:
        # Create a database connection.
        connection = pymysql.connect(
            host=host,
            port=port,
            user=user,
            passwd=password,
            db=database
        )
    
        # Get the cursor.
        with connection.cursor() as cursor:
            # Execute an SQL query.
            sql = "SELECT * FROM `<YOUR_TABLE_NAME>`"  # The name of the table from which you want to retrieve data.
            cursor.execute(sql)
    
            # Get the query results.
            results = cursor.fetchall()
            for row in results:
                print(row)
    
    finally:
        # Close the database connection.
        if 'connection' in locals() and connection.open:
            connection.close()
    

Go

This section uses Go 1.23.0 as an example to describe how to use the database/sql package and the go-sql-driver/mysql driver to connect to a PolarDB-X instance.

  1. Install the go-sql-driver/mysql driver by running the following command:

    go get -u github.com/go-sql-driver/mysql
  2. Connect to the instance. Replace the <HOST>, port number, <USER>, <PASSWORD>, <DATABASE>, and <YOUR_TABLE_NAME> parameters with your actual values.

    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-X instance.
        dbPort := "3306"         // The default port is 3306.
        dbUser := "<USER>"       // The database account.
        dbPass := "<PASSWORD>"   // The password of the database account.
        dbName := "<DATABASE>"   // The name of the database to which you want to connect.
    
        // Build the Data Source Name (DSN).
        dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", dbUser, dbPass, dbHost, dbPort, dbName)
    
        // Open the 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)
        }
    
        // Query the database version.
        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 table from which you want to retrieve data.
        if err != nil {
            log.Fatalf("Failed to execute query: %v", err)
        }
        defer rows.Close()
    
        // Process the query results.
        for rows.Next() {
            var id int
            var name string
            if err := rows.Scan(&id, &name); err != nil {
                log.Fatalf("Failed to scan row: %v", err)
            }
            fmt.Printf("ID: %d, Name: %s\n", id, name)
        }
    
        // Check for errors during iteration.
        if err := rows.Err(); err != nil {
            log.Fatalf("Error during iteration: %v", err)
        }
    }
    

FAQ

What do I do if an ECS instance fails to connect to a PolarDB-X instance?

Perform the following steps to troubleshoot the issue:

  1. Check whether the PolarDB-X instance is in the Running state.

  2. Check whether the database endpoint and port and the account and password are correct.

  3. Check the network connectivity. You can run the ping <database endpoint> or telnet <database endpoint> <port> command on the ECS instance to test the network connectivity.

  4. If you use a Internal Endpoint:

    1. Check whether the ECS instance and the PolarDB-X instance are in the same VPC. If they are not in the same VPC, you cannot use a Internal Endpoint. You can use one of the following solutions to place the ECS instance and the PolarDB-X instance in the same VPC:

      • Switch the VPC of the ECS instance.

      • If the PolarDB-X instance uses the default VPC, you can switch the VPC of the PolarDB-X instance.

      • Use Cloud Enterprise Network (CEN) to enable communication between the VPCs. For more information, see Connect VPCs in the same region.

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

  5. If you use a Public Endpoint, check whether the public IP address of the ECS instance is added to the whitelist of the PolarDB-X instance. For more information, see Configure a whitelist for the instance.

Note

You cannot use a Internal Endpoint to connect to a PolarDB-X instance from a virtual host or a simple application server.

What do I do if my on-premises environment fails to connect to a PolarDB-X instance?

Perform the following steps to troubleshoot the issue:

  1. Check whether the PolarDB-X instance is in the Running state.

  2. Check whether the database endpoint and port and the account and password are correct.

    Note

    The database endpoint must be a Public Endpoint. If you use an ECS instance that is in the same VPC as the PolarDB-X instance, you can use a Internal Endpoint.

  3. Check the network connectivity. You can run the ping <database endpoint> or telnet <database endpoint> <port> command in your on-premises environment to test the network connectivity.

  4. Check whether the public IP address or CIDR block of your on-premises environment is added to the whitelist of the PolarDB-X instance. For more information, see Configure a whitelist for the instance.

    To obtain the public IP address of your on-premises machine, use one of the following methods:

    • Linux: Open the terminal and run the curl ifconfig.me command.

    • Windows: Open the command prompt and run the curl ip.me command.

    • macOS: Open the terminal and run the curl ifconfig.me command.

    If your on-premises network uses a proxy, the IP address that you obtain using the preceding methods may not be the actual public IP address. In this case, add the 0.0.0.0/0 CIDR block to the whitelist of the PolarDB-X instance. After you connect to the instance, run the SHOW PROCESSLIST; command to obtain the actual public IP address. Then, add the actual public IP address to the whitelist and remove the 0.0.0.0/0 CIDR block.

    image

What do I do if a connection to a PolarDB-X instance fails with the "Access denied for user 'xxx'@'xxx' (using password: YES)" error?

This error indicates that the database account or password is incorrect. Check whether you entered them correctly. You can go to the PolarDB for Distributed console and choose Configuration Management > Account Management to manage database accounts and passwords.

What do I do if a connection to a PolarDB-X instance fails with the "Unknown MySQL server host 'xxx'" error?

This error indicates that the database endpoint is incorrect. Check whether you entered it correctly. The correct format is pxc-xxx.polarx.rds.aliyuncs.com. You can go to the PolarDB for Distributed console and choose Basic Information > Connection Information to manage your database endpoint.

What do I do if a connection to a PolarDB-X instance fails with the "Can't connect to MySQL server on 'xxx'" or "Connection timed out" error?

This issue may occur because the public IP address or CIDR block of your environment is not added to the whitelist of the PolarDB-X instance, or the public IP address or CIDR block that you entered is invalid.

To obtain the public IP address of your on-premises machine, use one of the following methods:

  • Linux: Open the terminal and run the curl ifconfig.me command.

  • Windows: Open the command prompt and run the curl ip.me command.

  • macOS: Open the terminal and run the curl ifconfig.me command.

If your on-premises network uses a proxy, the IP address that you obtain using the preceding methods may not be the actual public IP address. In this case, add the 0.0.0.0/0 CIDR block to the whitelist of the PolarDB-X instance. After you connect to the instance, run the SHOW PROCESSLIST; command to obtain the actual public IP address. Then, add the actual public IP address to the whitelist and remove the 0.0.0.0/0 CIDR block.

image

Best practices for database timeout settings

If your application uses a common Object-Relational Mapping (ORM) framework, such as SpringBoot, MyBatis, or Java Database Connectivity (JDBC) Driver, to access the database, you can set the client-side timeout for SQL queries at different levels, such as transactions, SQL statements, and packet forwarding. Examples include the transaction_timeout parameter in Spring, the statement_timeout parameter in MyBatis, and the query_timeout parameter in the JDBC MySQL driver.

Most of these client-side timeout mechanisms execute the Kill statement to interrupt queries. In a distributed database, the Kill statement is resource-intensive. Frequent execution of this statement consumes significant database system resources. Therefore, we recommend that you avoid frequent use of these timeout mechanisms.

As a best practice, use the socket_timeout parameter in the JDBC URL to specify the timeout period for SQL execution. This parameter relies on the timeout mechanism of the TCP protocol. When a timeout occurs, the Kill statement is not executed. The following code provides an example:

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
  <property name="url" value="jdbc:mysql://pxc-*****.public.polarx.rds.aliyuncs.com:3306/doc_test?socketTimeout=60000" />
  ...
  <property name="asyncInit" value="true" />
</bean>