All Products
Search
Document Center

PolarDB:Connect to a database

Last Updated:Jun 21, 2026

You can connect to a PolarDB-X instance by using Data Management (DMS), the MySQL CLI, third-party MySQL-compatible clients, or your application code.

Prerequisites

Before you connect to a PolarDB-X database, complete 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 view its basic information. In the Connection Information section, find the database endpoint and port.

    Note
    • Select an Intranet or a External network based on your access environment.

      • If you use an ECS instance to access PolarDB-X, and the ECS instance and PolarDB-X are in the same VPC, select Internal Network to achieve the best performance from PolarDB-X.

      • If you access PolarDB-X from your local environment, select Internet. You can obtain a public endpoint by clicking Apply for Public IP Address on the right. The Internet is the internet. Accessing the PolarDB-X instance over the Internet will not deliver optimal performance.

    • You cannot use an Internal Network to connect to a PolarDB-X instance from a virtual host or a Simple Application Server instance.

  • Create a database account.

  • Configure an instance whitelist

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

    On the whitelist settings page, you can view the list of whitelist groups and configure whitelists by using the corresponding buttons.

    Note
    • If you use an ECS instance to access PolarDB-X and the ECS instance is in the same VPC as the PolarDB-X instance, add the private IP address of the ECS instance to a new IP whitelist group.

    • If you use an ECS instance to access PolarDB-X but the ECS instance is in a different VPC from the PolarDB-X instance, add the public IP address of the ECS instance to a new IP whitelist group.

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

      To obtain the public IP address of your on-premises environment, perform one of the following steps:

      • For Linux operating systems: Open the terminal, enter the curl ifconfig.me command, and press Enter.

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

      • macOS: Open Terminal, enter the curl ifconfig.me command, and press Enter.

      If your local network is behind a proxy, the IP address that you obtain may not be your actual public IP address. You can add the IP address range 0.0.0.0/0 to the whitelist of the PolarDB-X instance. After you successfully connect to the instance, run the SHOW PROCESSLIST; command to obtain your actual public IP address and add it to the instance whitelist. Then, remove the IP address range 0.0.0.0/0 from the whitelist.

      39158 | aurora              | 100.104.108.247:39236 | information_schema | Sleep  |          47 |              | NULL
                                          Actual public IP address
      268459868 | polardb_mysql_account | 47.94.74.xxx:39160    | NULL               | Query  |           0 | starting     | SHOW PROCESSLIST
    • The IP address range0.0.0.0/0 allows access from all sources. Adding this range to an instance whitelist creates a high security risk. Do not add it to the whitelist unless absolutely necessary.

Connect to the database

You can connect to a database instance in several ways, depending on your workload. The following sections show common examples.

DMS

Data Management (DMS) is a graphical data management tool provided by Alibaba Cloud. It integrates a suite of services, including data management, schema management, user authorization, security auditing, data trending, data tracing, BI charts, performance optimization, and server management. You can use DMS to manage your PolarDB-X instance directly without needing other tools.

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

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

    Note
    • The first time you log on by using DMS, the control mode is Flexible Management by default. After you log on, you can change the control mode by editing the instance. For more information, see Edit instance information and Control modes.

    • After you configure the logon parameters, you can click Test Connectivity in the lower-left corner. If the connection fails, review the error message and check the information you entered, such as the account or password.

    • The system automatically attempts to add the IP addresses of the DMS servers to the whitelist of the PolarDB-X instance. If this attempt fails, you must add the IP addresses manually.

  3. After you log on, the PolarDB-X instance appears in the Connected Instances section of the left-side navigation pane. You can then manage the instance.

GUI client

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 support basic database operations, including CRUD and DDL. Advanced, client-specific features may not be supported by PolarDB-X.

The following steps use MySQL Workbench 8.0.29 as an example. Other clients follow a similar procedure.

  1. Install MySQL Workbench. For the official download link, see the MySQL Workbench 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 for the database account.

    Pass***233

MySQL CLI

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

Syntax:

mysql -h<endpoint> -P<port> -u<database_username> -p<database_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 for the database account.

Note

This parameter is required.

  • If you do not specify this parameter, you will be prompted again to enter the password at the Enter password prompt.

  • If you specify this parameter, do not leave a space between -p and the database password.

Pass***233

-D

The name of the database to which you want to connect.

Note

This parameter is optional.

test_db

Application

Connecting to a PolarDB-X instance from an application is similar to connecting to a standard MySQL database, requiring only the database endpoint, port, account, and password. The following examples show how to access a PolarDB-X instance using common programming languages:

Java

This example uses a Maven project and the MySQL JDBC driver to connect to a PolarDB-X instance.

  1. First, you need to add the MySQL JDBC driver dependency to the pom.xml file. The following is a code example:

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

    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) {
          // PolarDB-X instance endpoint, port, and database name
          String url = "jdbc:mysql://<HOST>:3306/<DATABASE>?useSSL=false&serverTimezone=UTC";
          // Database account
          String user = "<USER>";
          // Database password
          String password = "<PASSWORD>";
          try {
             Class.forName("com.mysql.cj.jdbc.Driver");
             Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement();
             // Table to query
             ResultSet rs = stmt.executeQuery("SELECT * FROM `<YOUR_TABLE_NAME>`");
             while(rs.next()) {
                // Column to retrieve
                System.out.println(rs.getString("<YOUR_TABLE_COLUMN_NAME>"));
             }
             rs.close();
             stmt.close();
             conn.close();
          } catch (Exception var7) {
             var7.printStackTrace();
          }
       }
    }

Python

This example uses Python 3 and the PyMySQL library to connect to a PolarDB-X instance.

  1. Install the PyMySQL library. If it is not installed, run the following command:

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

    import pymysql
    # Connection parameters
    host = '<HOST>'  # PolarDB-X instance endpoint
    port = 3306  # Default port is 3306
    user = '<USER>'  # Database account
    password = '<PASSWORD>'  # Database password
    database = '<DATABASE>'  # Target database name
    try:
        # Create a database connection
        connection = pymysql.connect(
            host=host,
            port=port,
            user=user,
            passwd=password,
            db=database
        )
        # Create a cursor
        with connection.cursor() as cursor:
            # Run an SQL query
            sql = "SELECT * FROM `<YOUR_TABLE_NAME>`"  # Table to query
            cursor.execute(sql)
            # Fetch 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 example uses Go 1.23.0, the database/sql package, and the go-sql-driver/mysql driver to connect to a PolarDB-X instance.

  1. First, you need to install the go-sql-driver/mysql driver. You can install it by running the following command:

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

    package main
    import (
        "database/sql"
        "fmt"
        "log"
        _ "github.com/go-sql-driver/mysql"
    )
    func main() {
        // Connection parameters
        dbHost := "<HOST>"       // PolarDB-X instance endpoint
        dbPort := "3306"         // Default port is 3306
        dbUser := "<USER>"       // Database account
        dbPass := "<PASSWORD>"   // Database password
        dbName := "<DATABASE>"   // Target database name
        // Build the DSN (Data Source Name)
        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()
        // Ping the server to test the connection
        err = db.Ping()
        if err != nil {
            log.Fatalf("Failed to ping database: %v", err)
        }
        // Query the server 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)
        // Run an SQL query
        rows, err := db.Query("SELECT * FROM `<YOUR_TABLE_NAME>`") // Table to query
        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 row iteration
        if err := rows.Err(); err != nil {
            log.Fatalf("Error during iteration: %v", err)
        }
    }
    

FAQ

ECS cannot connect to aPolarDB-X instance

Follow these steps to troubleshoot the issue:

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

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

  3. Check for network factors by running ping <database endpoint> or telnet <database endpoint> <port> in an ECS instance to test network connectivity.

  4. If you are using an Internal Network:

    1. Check whether the ECS instance and the PolarDB-X instance are in the same VPC. If not, you cannot use the Internal Network. You can use one of the following methods to place the ECS and PolarDB-X instances 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 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 an instance whitelist.

  5. If you are using a Internet, 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 an instance whitelist.

Note

You cannot use an Internal Network to connect to a PolarDB-X instance from a virtual host or a Simple Application Server instance.

Cannot connect to a PolarDB-X instance from a local environment

Follow these steps to troubleshoot the issue:

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

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

    Note

    You must use a Internet to connect from an on-premises environment. An Internal Network can only be used when the client and the PolarDB-X instance are in the same VPC.

  3. To check for network issues, you can run ping <database endpoint> or telnet <database endpoint> <port> in your local environment to test 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 an instance whitelist.

    To obtain the public IP address of your on-premises environment, perform one of the following steps:

    • For Linux operating systems: Open the terminal, enter the curl ifconfig.me command, and press Enter.

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

    • macOS: Open Terminal, enter the curl ifconfig.me command, and press Enter.

    If your local network is behind a proxy, the IP address that you obtain may not be your actual public IP address. You can add the IP address range 0.0.0.0/0 to the whitelist of the PolarDB-X instance. After you successfully connect to the instance, run the SHOW PROCESSLIST; command to obtain your actual public IP address and add it to the instance whitelist. Then, remove the IP address range 0.0.0.0/0 from the whitelist.

    39158 | aurora              | 100.104.108.247:39236 | information_schema | Sleep  |          47 |              | NULL
                                        Actual public IP address
    268459868 | polardb_mysql_account | 47.94.74.xxx:39160    | NULL               | Query  |           0 | starting     | SHOW PROCESSLIST

Unable to connect to a PolarDB-X instance, and you receive the error: Access denied for user 'xxx'@'xxx' (using password: YES)

An error message such as "Access denied for user 'xxx'@'xxx' (using password: YES)" indicates an incorrect database account or password. Verify your credentials. You can go to the PolarDB for Distributed console and choose Configuration and Management > Accounts to manage your database account and password.

Cannot connect to a PolarDB-X instance: 'Unknown MySQL server host 'xxx'' error

This error indicates that the database endpoint is incorrect. Ensure that the endpoint is correct and follows the format pxc-xxx.polarx.rds.aliyuncs.com. You can go to the PolarDB for Distributed console and find your database endpoint in the Basic Information > Connection Information section.

Cannot connect to aPolarDB-X instance, with the error: Can't connect to MySQL server on 'xxx' or Connection timed out

This can occur if the public IP of your environment is not added to the whitelist of the PolarDB-X instance, or if the whitelist entry is incorrect.

To obtain the public IP address of your on-premises environment, perform one of the following steps:

  • For Linux operating systems: Open the terminal, enter the curl ifconfig.me command, and press Enter.

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

  • macOS: Open Terminal, enter the curl ifconfig.me command, and press Enter.

If your local network is behind a proxy, the IP address that you obtain may not be your actual public IP address. You can add the IP address range 0.0.0.0/0 to the whitelist of the PolarDB-X instance. After you successfully connect to the instance, run the SHOW PROCESSLIST; command to obtain your actual public IP address and add it to the instance whitelist. Then, remove the IP address range 0.0.0.0/0 from the whitelist.

39158 | aurora              | 100.104.108.247:39236 | information_schema | Sleep  |          47 |              | NULL
                                    Actual public IP address
268459868 | polardb_mysql_account | 47.94.74.xxx:39160    | NULL               | Query  |           0 | starting     | SHOW PROCESSLIST

Database timeout best practices

If your application uses a common Object-Relational Mapping (ORM) framework, such as Spring Boot, MyBatis, and a JDBC driver, the framework often lets you set client-side timeouts for SQL queries across several layers, such as transactions, SQL statements, and network I/O. Examples include Spring’s transaction_timeout, MyBatis’s statement_timeout, and the MySQL JDBC driver’s query_timeout.

Essentially, most of these client-side timeout mechanisms need to execute a database Kill statement to interrupt queries. In distributed database scenarios, Kill statements are costly to execute, and frequent execution consumes a significant amount of database system resources. Therefore, it is not recommended to use these timeout mechanisms extensively.

As a best practice, your application should directly use the socket_timeout parameter (network socket timeout) in the JDBC URL to specify the SQL execution timeout. This is because the parameter relies on the TCP protocol's own timeout mechanism, and a Kill statement is not triggered when a timeout occurs. For 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>