All Products
Search
Document Center

PolarDB:Connect to a database

Last Updated:Mar 28, 2026

PolarDB for Xscale supports connections through Data Management (DMS), MySQL command line, third-party clients, and third-party program code that complies with the official MySQL interaction protocol.

Choose your connection method based on your goal:

Prerequisites

Before you begin, ensure that you have:

  • The instance endpoint and port (see step 1 below)

  • A database account (create one if you haven't done so)

  • Your IP address added to the instance whitelist (see step 3 below)

  • Obtain the database endpoint and port

    Step 1: Get your endpoint and port

    In the PolarDB Distributed Edition console, click the instance ID in Instance List to open the instance page. In Connection Information, copy the endpoint and port.

    image
    Select Private Network or Public Network based on your access environment:
    Private Network — use this when your Elastic Compute Service (ECS) instance and PolarDB for Xscale are in the same Virtual Private Cloud (VPC). This gives the best performance.
    Public Network — use this when connecting from a local environment, or when ECS and PolarDB for Xscale are in different VPCs. Click Request Public Network Address to enable a public endpoint. Public network connections have higher latency than private network connections. Virtual hosts and lightweight servers cannot connect using a private network address.
  • Step 2: Create a database account

    Create a database account for the instance if you haven't done so.

  • Configure a whitelist for the instance

    Step 3: Configure the IP whitelist

    In the console, go to Configuration And Management > Security Management and add your IP address to the whitelist. For detailed steps, see Set whitelist.

    image

    Configure the whitelist based on your network environment:

    EnvironmentAction
    ECS in the same VPC as PolarDB for XscaleSkip this step. The system automatically adds the VPC CIDR block to the default whitelist group.
    ECS in a different VPCAdd the public IP address of ECS, or add the ECS security group to the instance whitelist.
    Local environmentAdd your local public IP address to a new IP whitelist group.

    To find your public IP address:

    • Linux or macOS: run curl ifconfig.me in a terminal.

    • Windows: run curl ip.me in a command prompt.

    If your network uses a proxy, the command above may not return your real public IP. In that case, temporarily add the CIDR block 0.0.0.0/0 to the whitelist, connect to the instance, run SHOW PROCESSLIST; to get your real IP, add it to the whitelist, then remove 0.0.0.0/0.

    Warning

    The CIDR block 0.0.0.0/0 allows access from all sources. Only use it temporarily during troubleshooting, then remove it immediately after you identify your real IP.

    image

Use DMS

Data Management Service (DMS) is Alibaba Cloud's graphical data management tool. It integrates data management, structure management, user authorization, security audit, data trend, data tracking, BI chart, performance and optimization, and server management.

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

    image

  2. Enter the Database Account and Database Password, then click Log On.

    The first time you log on through DMS, the control mode defaults to Flexible Management. To change it later, see Edit instance information and Control modes. Click Test Connection in the lower-left corner to verify credentials before logging on. If the test fails, check the account name and password. DMS automatically tries to add its server address to the instance whitelist. If the automatic addition fails, add it manually.

    image

  3. After logging on, the instance appears under Logged-in Instances in the left navigation pane.

    image

Use a third-party client

PolarDB for Xscale supports the following GUI clients. Download your preferred client from its official website.

  • MySQL Workbench (recommended)

  • SQLyog

  • Sequel Pro

  • Navicat for MySQL

Third-party clients support basic operations — data insert, update, delete, query, and DDL. Advanced tool-specific features may not be fully supported by PolarDB for Xscale.

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

  1. Download and install MySQL Workbench.

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

  3. Enter the connection details and click OK.

    ParameterDescriptionExample
    HostnameThe instance endpoint.pxc-xxx.polarx.rds.aliyuncs.com
    PortThe port number. Default: 3306.3306
    UsernameThe database account.polardb_x_user
    PasswordThe database account password.Pass***233

    连接界面

Use the MySQL command line

If the MySQL client is installed on your server, connect directly from the command line.

Syntax:

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
ParameterDescriptionExample
-hThe instance endpoint.pxc-xxx.polarx.rds.aliyuncs.com
-PThe port number. Default: 3306. Can be omitted when using the default port.3306
-uThe database account.polardb_x_user
-pThe database account password. No space between -p and the password. If omitted, you are prompted to enter the password after Enter password:.Pass***233
-DThe database name. Optional.test_db

Connect from an application

PolarDB for Xscale uses the same connection interface as MySQL. Replace the endpoint, port, account, and password in your existing MySQL connection code.

Java

This example uses a Maven project with the MySQL JDBC driver (MySQL Connector/J).

  1. Add the MySQL JDBC driver dependency to pom.xml:

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.27</version>
    </dependency>
  2. Replace <HOST>, <USER>, <PASSWORD>, <DATABASE>, <YOUR_TABLE_NAME>, and <YOUR_TABLE_COLUMN_NAME> 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) {
          // PolarDB instance connection address, port, and database name to connect to
          String url = "jdbc:mysql://<HOST>:3306/<DATABASE>?useSSL=false&serverTimezone=UTC";
          // Database account
          String user = "<USER>";
          // 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();
             // Name of the data table to retrieve
             ResultSet rs = stmt.executeQuery("SELECT * FROM `<YOUR_TABLE_NAME>`");
    
             while(rs.next()) {
                // Name of the column in the data table 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 with the PyMySQL library.

  1. Install PyMySQL:

    pip3 install PyMySQL
  2. Replace <HOST>, <USER>, <PASSWORD>, <DATABASE>, and <YOUR_TABLE_NAME> with your actual values:

    import pymysql
    
    # Database connection parameters
    host = '<HOST>'  # PolarDB instance connection address
    port = 3306  # Default port 3306
    user = '<USER>'  # Database account
    password = '<PASSWORD>'  # Password of the database account
    database = '<DATABASE>'  # Database name to connect to
    
    try:
        # Create a database connection
        connection = pymysql.connect(
            host=host,
            port=port,
            user=user,
            passwd=password,
            db=database
        )
    
        # Obtain the operation cursor
        with connection.cursor() as cursor:
            # Execute SQL query
            sql = "SELECT * FROM `<YOUR_TABLE_NAME>`"  # Name of the data table to retrieve
            cursor.execute(sql)
    
            # Obtain 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 with the database/sql package and the go-sql-driver/mysql driver.

  1. Install the MySQL driver:

    go get -u github.com/go-sql-driver/mysql
  2. Replace <HOST>, <USER>, <PASSWORD>, <DATABASE>, and <YOUR_TABLE_NAME> with your actual values:

    package main
    
    import (
        "database/sql"
        "fmt"
        "log"
        _ "github.com/go-sql-driver/mysql"
    )
    
    func main() {
        // Database connection parameters
        dbHost := "<HOST>"       // PolarDB instance connection address
        dbPort := "3306"         // Default port 3306
        dbUser := "<USER>"       // Database account
        dbPass := "<PASSWORD>"   // Password of the database account
        dbName := "<DATABASE>"   // Database name to connect to
    
        // Construct 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()
    
        // Test the connection
        err = db.Ping()
        if err != nil {
            log.Fatalf("Failed to ping database: %v", err)
        }
    
        // Create an operation cursor
        var result string
        err = db.QueryRow("SELECT VERSION()").Scan(&result)
        if err != nil {
            log.Fatalf("Failed to execute query: %v", err)
        }
    
        // Output the database version
        fmt.Printf("Connected to database, version: %s\n", result)
    
        // Execute SQL query
        rows, err := db.Query("SELECT * FROM `<YOUR_TABLE_NAME>`") // Name of the data table to retrieve
        if err != nil {
            log.Fatalf("Failed to execute query: %v", err)
        }
        defer rows.Close()
    
        // Process 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
        if err := rows.Err(); err != nil {
            log.Fatalf("Error during iteration: %v", err)
        }
    }

Timeout best practices

When using ORM frameworks such as Spring Boot + MyBatis + JDBC Driver, the ORM layer provides several timeout mechanisms — for example, Spring's transaction_timeout, MyBatis's statement_timeout, and JDBC MySQL Driver's query_timeout. Most of these work by issuing a KILL statement to interrupt the query.

In a distributed database, KILL statements are expensive. Frequent execution consumes significant database resources.

Instead, use the socketTimeout parameter in the JDBC URL. This sets a TCP-level timeout that does not generate KILL statements when triggered.

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

socketTimeout=60000 sets a 60-second SQL execution timeout at the TCP layer.

Troubleshooting

ECS cannot connect to the instance

Work through the following checks in order:

  1. Verify the instance status is Running in the console.

  2. Confirm the endpoint, port, account, and password are correct.

  3. Test network connectivity from ECS:

    ping <endpoint>
    telnet <endpoint> <port>
  4. If using a Private Network address:

    • Verify ECS and the PolarDB for Xscale instance are in the same VPC. If not, you cannot use a private network address. To resolve this, either:

      • Switch the VPC where ECS is located.

      • If the PolarDB for Xscale instance uses the default VPC, switch the VPC where the PolarDB for Xscale instance is located.

      • Use Cloud Enterprise Network (CEN) to connect the two VPCs. See Connect VPCs in the same region.

    • Verify the private IP address, CIDR block, or security group of ECS has been added to the instance whitelist. See Set whitelist.

  5. If using a Public Network address, verify the public IP address or security group of ECS has been added to the instance whitelist.

Virtual hosts and lightweight servers cannot connect using a private network address.

Local environment cannot connect to the instance

Work through the following checks in order:

  1. Verify the instance status is Running in the console.

  2. Confirm you are using the Public Network endpoint, not the private network endpoint. Copy it from Basic Information > Connection Information.

  3. Confirm the port, account, and password are correct.

  4. Test network connectivity from your local environment:

    ping <endpoint>
    telnet <endpoint> <port>
  5. Verify your local public IP address has been added to the instance whitelist. To find your public IP: If your network uses a proxy, the command may not return your real public IP. Temporarily add 0.0.0.0/0 to the whitelist, connect, run SHOW PROCESSLIST; to get your real IP, add it to the whitelist, then remove 0.0.0.0/0.

    • Linux or macOS: run curl ifconfig.me.

    • Windows: run curl ip.me.

    image

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

The account or password is incorrect. To reset or verify credentials, go to the PolarDB Distributed Edition console and open Configuration And Management > Account Management. See Manage database accounts.

Error:Unknown MySQL server host 'xxx'

The endpoint is incorrect. The correct format is pxc-xxx.polarx.rds.aliyuncs.com. Copy the correct endpoint from Basic Information > Connection Information in the PolarDB Distributed Edition console.

Error:Can't connect to MySQL server on 'xxx'orConnection timed out

Your current IP address is not in the instance whitelist, or the IP address you added contains a typo. To find your public IP address:

  • Linux or macOS: run curl ifconfig.me.

  • Windows: run curl ip.me.

If your network uses a proxy, the command may not return your real public IP. Temporarily add 0.0.0.0/0 to the whitelist, connect, run SHOW PROCESSLIST; to get your real IP, add it to the whitelist, then remove 0.0.0.0/0.

image