All Products
Search
Document Center

PolarDB:Connect to a database

Last Updated:Mar 28, 2026

PolarDB-X is MySQL-protocol compatible, so you can connect to it using Data Management (DMS), the MySQL CLI, any MySQL-compatible GUI client, or application code written in Java, Python, or Go.

Choose a connection method

Use the table below to identify the right method for your environment:

EnvironmentRecommended method
Alibaba Cloud console, no local client neededDMS
Local GUI tool preferredMySQL Workbench or another GUI client
Command line preferredMySQL CLI
Connecting from application codeJava, Python, or Go driver

Prerequisites

Before you begin, make sure you have:

  • The database endpoint and port for your instance — go to the PolarDB for Distributed console, click the instance ID in the Instances list, and find both values under Basic Information > Connection Information

    Internal endpoints cannot be used from a virtual host or Simple Application Server.

    Choose the right endpoint type:

    Endpoint typeWhen to use
    Internal endpointYour Elastic Compute Service (ECS) instance and PolarDB-X instance are in the same Virtual Private Cloud (VPC). Provides the best performance.
    Public endpointConnecting from an on-premises machine or an ECS instance in a different VPC. Click Apply for Public Endpoint to get one. Internet access works but does not provide optimal performance.

    image

  • A database account — create one if you have not done so

  • An IP whitelist configured for the instance — go to Configuration Management > Security Management and add the IP address or CIDR block of your client. For full instructions, see Configure whitelists If your network uses a proxy, the IP returned above may not be your actual public IP. In that case, add 0.0.0.0/0 to the whitelist temporarily, connect to the instance, run SHOW PROCESSLIST; to find your real IP, add it to the whitelist, then remove 0.0.0.0/0.

    Warning

    The 0.0.0.0/0 CIDR block allows access from all IP addresses. Remove it from the whitelist as soon as you have identified your actual IP.

    Finding your public IP address:

    OSCommand
    Linux / macOScurl ifconfig.me
    Windowscurl ip.me

    image

    image

Connect using DMS

Data Management (DMS) is a browser-based management tool provided by Alibaba Cloud. It covers data management, schema management, user authorization, security audit, data trends, data tracking, BI charts, performance optimization, and server management — no additional client software needed.

  1. In the PolarDB for Distributed console, click the instance ID, then click Log On To Database in the upper-right corner.

    image

  2. Enter your Database Account and Database Password, then click Logon.

    Click Test Connection before logging on to verify your credentials. If the test fails, check the account and password you entered. DMS automatically adds its server IP addresses to the ApsaraDB whitelist. If the addresses are not added automatically, add them manually. By default, the control mode is Flexible Management when you first log on to DMS. To change it after logging on, see Modify instance information and Control modes.

    image

  3. After you log on, the instance appears in Instances Connected in the left navigation pane.

    image

Connect using a GUI client

PolarDB-X works with any MySQL-compatible GUI client. Recommended options:

  • MySQL Workbench (recommended)

  • SQLyog

  • Sequel Pro

  • Navicat for MySQL

GUI clients support standard CRUD and DDL operations. Advanced client-specific features may not be supported by PolarDB-X.

The following steps use MySQL Workbench 8.0.29. Other clients follow a similar pattern.

  1. Download and install MySQL Workbench.

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

  3. Enter your connection details and click OK.

    ParameterDescriptionExample
    HostnameThe database endpointpxc-xxx.polarx.rds.aliyuncs.com
    PortThe port number (default: 3306)3306
    UsernameYour database accountpolardb_x_user
    PasswordThe account passwordPass***233

    连接界面

Connect using the MySQL CLI

If MySQL is installed on your machine, connect with a single command:

mysql -h<endpoint> -P<port> -u<username> -p<password> -D<database>

Example:

mysql -hpxc-xxx.polarx.rds.aliyuncs.com -P3306 -upolardb_mysql_user -pPass***233 -Dtest_db
FlagDescriptionExample
-hDatabase endpointpxc-xxx.polarx.rds.aliyuncs.com
-PPort number. Omit if using the default port (3306).3306
-uDatabase accountpolardb_x_user
-pPassword. Required. Do not add a space between -p and the password. Omit the value to be prompted interactively.Pass***233
-DDatabase name. Optional.test_db

Connect from application code

PolarDB-X accepts standard MySQL connections. Replace the endpoint, port, account, and password in any MySQL driver or library you already use.

Java

This example uses Maven with the MySQL JDBC driver.

  1. Add the driver dependency to your pom.xml:

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

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

Python

This example uses Python 3 with PyMySQL.

  1. Install PyMySQL:

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

    import pymysql
    
    host = '<HOST>'         # Database endpoint
    port = 3306             # Default port
    user = '<USER>'         # Database account
    password = '<PASSWORD>' # Account password
    database = '<DATABASE>' # Target database
    
    try:
        connection = pymysql.connect(
            host=host,
            port=port,
            user=user,
            passwd=password,
            db=database
        )
    
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM `<YOUR_TABLE_NAME>`")
            results = cursor.fetchall()
            for row in results:
                print(row)
    
    finally:
        if 'connection' in locals() and connection.open:
            connection.close()

Go

This example uses Go 1.23.0 with the database/sql package and the go-sql-driver/mysql driver.

  1. Install the driver:

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

    package main
    
    import (
        "database/sql"
        "fmt"
        "log"
        _ "github.com/go-sql-driver/mysql"
    )
    
    func main() {
        dbHost := "<HOST>"     // Database endpoint
        dbPort := "3306"       // Default port
        dbUser := "<USER>"     // Database account
        dbPass := "<PASSWORD>" // Account password
        dbName := "<DATABASE>" // Target database
    
        // 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)
    
        db, err := sql.Open("mysql", dsn)
        if err != nil {
            log.Fatalf("Failed to open connection: %v", err)
        }
        defer db.Close()
    
        // Verify the connection
        if err = db.Ping(); err != nil {
            log.Fatalf("Failed to connect: %v", err)
        }
    
        // Print the database version to confirm a successful connection
        var version string
        if err = db.QueryRow("SELECT VERSION()").Scan(&version); err != nil {
            log.Fatalf("Query failed: %v", err)
        }
        fmt.Printf("Connected. Database version: %s\n", version)
    
        // Query a table
        rows, err := db.Query("SELECT * FROM `<YOUR_TABLE_NAME>`")
        if err != nil {
            log.Fatalf("Query failed: %v", err)
        }
        defer rows.Close()
    
        for rows.Next() {
            var id int
            var name string
            if err := rows.Scan(&id, &name); err != nil {
                log.Fatalf("Scan failed: %v", err)
            }
            fmt.Printf("ID: %d, Name: %s\n", id, name)
        }
    
        if err = rows.Err(); err != nil {
            log.Fatalf("Row iteration error: %v", err)
        }
    }

Best practices for timeout settings

If your application uses an Object-Relational Mapping (ORM) framework such as Spring Boot, MyBatis, or a Java Database Connectivity (JDBC) driver, avoid relying on client-side timeout mechanisms like transaction_timeout (Spring), statement_timeout (MyBatis), or query_timeout (JDBC MySQL driver).

These mechanisms terminate queries by running a Kill statement. In a distributed database, Kill is resource-intensive — frequent use consumes significant system resources.

Instead, set socketTimeout in your JDBC URL. This uses the TCP-level timeout and does not trigger a Kill statement:

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

Troubleshooting

The following errors are the most common connection issues. Use Ctrl+F to search for your exact error message.

Error messageLikely cause
Access denied for user 'xxx'@'xxx' (using password: YES)Incorrect account or password
Unknown MySQL server host 'xxx'Incorrect endpoint
Can't connect to MySQL server on 'xxx' / Connection timed outIP not whitelisted, or invalid IP or CIDR block

ECS instance cannot connect to PolarDB-X

  1. Confirm the PolarDB-X instance is in the Running state.

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

  3. Test network connectivity from the ECS instance:

    ping <database endpoint>
    telnet <database endpoint> <port>
  4. If using an internal endpoint, confirm ECS and PolarDB-X are in the same VPC. If they are not, choose one of these options: Then confirm the private IP address or CIDR block of the ECS instance is in the whitelist.

    • Switch the VPC of the ECS instance.

    • Switch the VPC of the PolarDB-X instance (if it uses the default VPC).

    • Use Cloud Enterprise Network (CEN) to connect the two VPCs.

  5. If using a public endpoint, confirm the public IP of the ECS instance is in the whitelist.

Internal endpoints cannot be used from a virtual host or Simple Application Server.

On-premises environment cannot connect to PolarDB-X

  1. Confirm the instance is in the Running state.

  2. Verify the endpoint (must be a public endpoint), port, account, and password.

  3. Test network connectivity:

    ping <database endpoint>
    telnet <database endpoint> <port>
  4. Confirm your public IP is in the whitelist. See the IP detection commands in Prerequisites.

"Access denied for user 'xxx'@'xxx' (using password: YES)"

The account or password is incorrect. Go to the PolarDB for Distributed console and choose Configuration Management > Account Management to reset or verify your credentials.

"Unknown MySQL server host 'xxx'"

The endpoint is incorrect. The correct format is pxc-xxx.polarx.rds.aliyuncs.com. Go to the PolarDB for Distributed console and check Basic Information > Connection Information.

"Can't connect to MySQL server on 'xxx'" or "Connection timed out"

Your IP address is not in the whitelist, or the IP or CIDR block you entered is invalid. Find your public IP using the commands in Prerequisites and add it to the whitelist.

What's next