All Products
Search
Document Center

PolarDB:Connect to a database

Last Updated:Mar 14, 2025

PolarDB-X 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.

Preparations

Before connecting to the PolarDB-X database, you need to perform the following operations:

  • Obtain the database connection address and port

    You can go to the PolarDB Distributed Edition Console, click the target instance ID in the Instance List to enter the instance basic information page. In the Connection Information area, obtain the database connection address and port.

    image

    Note
    • Select Intranet or Internet based on your access environment.

      • If you are using ECS to access PolarDB-X and ECS and PolarDB-X are in the same VPC, select Private Network to achieve the best performance of PolarDB-X.

      • If you are accessing PolarDB-X from a local environment, select Public Network. Click Request Public Network Address on the right side of the public network address. The Public Network is the Internet, and accessing through the Public Network will not achieve the best performance of the PolarDB-X instance.

    • Currently, it is not supported to use virtual hosts and lightweight servers to connect to PolarDB-X instances using Private Network addresses.

  • Create a database account.

  • Set the instance whitelist

    You can go to the PolarDB Distributed Edition Console, and click the target instance ID in the Instance List to enter the instance product page. In Configuration And Management > Security Management, Configure the IP whitelist or Add A New Whitelist Group. For specific operations, see Set Whitelist.

    image

    Note
    • If you are using ECS to access PolarDB-X and ECS and PolarDB-X are in the same VPC, ignore this step. The system has added the VPC CIDR block where ECS is located to the default group.

    • If you are using ECS to access PolarDB-X but ECS and PolarDB-X are not in the same VPC, you can choose to add the public IP address of ECS to a new IP whitelist group or add the security group where ECS is located to the instance whitelist.

    • If you are accessing PolarDB-X from a local environment, add the public IP address of your local environment to a new IP whitelist group.

      The method to obtain the public IP address of the local environment is as follows:

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

      • Windows operating system: Open the command prompt, enter the command curl ip.me, and press Enter.

      • macOS operating system: Open the terminal, enter the command curl ifconfig.me, and press Enter.

      If there is a proxy or other situation in your local network environment, the IP obtained by the above method may not be your real public IP. You can add the IP segment 0.0.0.0/0 to the PolarDB-X instance whitelist. After successfully connecting to the instance, execute the command SHOW PROCESSLIST; to obtain the real public IP address and add it to the instance whitelist. Then delete the IP segment 0.0.0.0/0 from the whitelist.

      image

    • The IP segment 0.0.0.0/0 means allowing all access sources to access the instance. Setting it in the instance whitelist poses a great risk. Do not add it to the whitelist unless necessary.

Connect to a database

There are many ways to connect to a database instance. You can choose the appropriate connection method based on your actual business needs. The following are some examples of connecting to a database instance:

Use DMS to connect to a database

DMS is a graphical data management tool provided by Alibaba Cloud. It is a data management service that integrates data management, structure management, user authorization, security audit, data trend, data tracking, BI chart, performance and optimization, and server management. You can manage your PolarDB-X instance directly on DMS without using other tools.

  1. Go to the PolarDB Distributed Edition Console, click the target instance ID in the Instance List to enter the instance product page. Click Log On To Database in the upper right corner of the page.

    image

  2. In the pop-up dialog box, enter the Database Account and Database Password created in the PolarDB-X instance, and click Log On.

    image

    Note
    • When logging on through DMS for the first time, the control mode defaults to Flexible Management. After successful login, you can also modify the control mode through the edit instance function. For more information, see Edit Instance Information and Control Mode.

    • After configuring the login parameters, you can click Test Connection in the lower left corner. If the test connection fails, check the entered instance information according to the error prompt, such as whether the account or password is correct.

    • The system will automatically try to add the server access address of DMS to the whitelist of the cloud database. If the automatic addition fails, please add it manually.

  3. After logging in, you can view the PolarDB-X instance you are logged into within the Logged-in Instances section of the left-side navigation pane and carry out the necessary management operations.

    image

Use a client to connect to a database

PolarDB-X supports connections through the following third-party clients. You can download the client from the corresponding official website.

  • MySQL Workbench (recommended)

  • SQLyog

  • Sequel Pro

  • Navicat for MySQL

Note

Third-party GUI clients can perform basic database operations, including data addition, deletion, modification, query, and DDL operations. For advanced features of the tool, PolarDB-X may not support them.

The following uses MySQL Workbench version 8.0.29 as an example. The operations of other clients are similar.

  1. Install MySQL Workbench. For the official download address, see MySQL Workbench Download Page.

  2. Open MySQL Workbench, select Database > Connect to Database.

  3. Enter the connection information and click OK.

    连接界面

    Parameter

    Description

    Example

    Hostname

    Database connection address.

    pxc-xxx.polarx.rds.aliyuncs.com

    Port

    The port number of the database connection address, corresponding to the database connection address.

    Note

    The default port is 3306.

    3306

    Username

    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 your server has the MySQL client installed, you can connect to the PolarDB-X instance through the command line.

Syntax:

mysql -h<connection address> -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

Database connection address.

pxc-xxx.polarx.rds.aliyuncs.com

-P

The port number of the database connection address, corresponding to the database connection address.

Note
  • The default port is 3306.

  • If the port number is the default port, this parameter can be omitted.

3306

-u

Database account.

polardb_x_user

-p

The password of the database account.

Note

This parameter is required.

  • If this parameter is not filled in, you will be prompted to enter the password again after Enter password.

  • If this parameter is filled in, there should be no space between -p and the database password.

Pass***233

-D

The name of the database to log on to.

Note

This parameter is not required.

test_db

Use an application to connect to a database

The method of connecting to a PolarDB-X instance is the same as connecting to other MySQL databases. You only need to replace the database connection address, port, account, and password. The following lists how to access the PolarDB database through applications in some development languages:

Java

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

  1. First, you need to add the MySQL JDBC driver dependency in the pom.xml file. 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 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 Python3 to connect to a PolarDB-X instance using the PyMySQL library.

  1. First, you need to install the PyMySQL library. If you have not installed it, you can install it using 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
    
    # 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 go1.23.0 to connect to a PolarDB-X instance using the database/sql package and the go-sql-driver/mysql driver.

  1. First, you need to install the go-sql-driver/mysql driver. You can install it using 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() {
        // 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)
        }
    }
    

FAQ

ECS cannot connect toPolarDB-Xinstance

Please troubleshoot according to the following steps:

  1. Check whether the running status of the PolarDB-X instance is Running.

  2. Check whether the database connection address, port, account, and password are correct.

  3. Check the network factors. You can execute ping database connection address or telnet database connection address port in ECS to test network connectivity.

  4. If you are using a Private Network address:

    1. Check whether ECS and the PolarDB-X instance are in the same VPC. If they are not in the same VPC, you cannot use the Private Network address. You can use any of the following solutions to make ECS and the PolarDB-X instance in the same VPC:

      • Switch the VPC where ECS is located.

      • If the PolarDB-X instance uses the default VPC, you can switch the VPC where the PolarDB-X instance is located.

      • Use Cloud Enterprise Network to achieve interconnection between VPCs. For more information, see Interconnection between VPCs in the same region.

    2. Check whether the private IP address, IP segment, or security group of ECS has been added to the whitelist of the PolarDB-X instance. For more information, see Set the instance whitelist.

  5. If you are using a Public Network address, check whether the public IP address or security group of ECS has been added to the whitelist of the PolarDB-X instance. For more information, see Set the instance whitelist.

Note

Currently, it is not supported to use virtual hosts and lightweight servers to connect to PolarDB-X instances using Private Network addresses.

Local environment cannot connect toPolarDB-Xinstance

Please troubleshoot according to the following steps:

  1. Verify that the PolarDB-X instance is in a Running status.

  2. Check whether the database connection address, port, account, and password are correct.

    Note

    The database connection address must be a Public Network address. If you are using ECS and are in the same VPC as the PolarDB-X instance, you can use the Private Network address.

  3. Check the network factors. You can execute ping <database connection address> or telnet <database connection address> <port> in the local environment to test network connectivity.

  4. Check whether the public IP address or IP segment of the local environment has been added to the whitelist of the PolarDB-X instance. For more information, see Set the instance whitelist.

    The method to obtain the public IP address of the local environment is as follows:

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

    • Windows operating system: Open the command prompt, enter the command curl ip.me, and press Enter.

    • macOS operating system: Open the terminal, enter the command curl ifconfig.me, and press Enter.

    If there is a proxy or other situation in your local network environment, the IP obtained by the above method may not be your real public IP. You can add the IP segment 0.0.0.0/0 to the PolarDB-X instance whitelist. After successfully connecting to the instance, execute the command SHOW PROCESSLIST; to obtain the real public IP address and add it to the instance whitelist. Then delete the IP segment 0.0.0.0/0 from the whitelist.

    image

Cannot connect toPolarDB-Xinstance, error: Access denied for user 'xxx'@'xxx' (using password: YES)

The database account or password is incorrect. Please check whether you have entered it correctly. You can go to the PolarDB distributed edition console, and in Configuration And Management > Account Management manage database accounts and passwords.

Cannot connect toPolarDB-Xinstance, error: Unknown MySQL server host 'xxx'

The database connection address is incorrect. Please check whether you have entered it correctly. The correct format is pxc-xxx.polarx.rds.aliyuncs.com. You can go to the PolarDB Distributed Edition Console, and manage your database connection address in Basic Information > Connection Information.

Cannot connect toPolarDB-Xinstance, error: Can't connect to MySQL server on 'xxx' or Connection timed out

It may be that the public IP address or IP segment of your current environment has not been added to the whitelist of the PolarDB-X instance, or there is an error in the public IP address or IP segment you filled in.

The method to obtain the public IP address of the local environment is as follows:

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

  • Windows operating system: Open the command prompt, enter the command curl ip.me, and press Enter.

  • macOS operating system: Open the terminal, enter the command curl ifconfig.me, and press Enter.

If there is a proxy or other situation in your local network environment, the IP obtained by the above method may not be your real public IP. You can add the IP segment 0.0.0.0/0 to the PolarDB-X instance whitelist. After successfully connecting to the instance, execute the command SHOW PROCESSLIST; to obtain the real public IP address and add it to the instance whitelist. Then delete the IP segment 0.0.0.0/0 from the whitelist.

image

Recommended practices for database timeout settings

If your application uses some common ORM frameworks (such as SpringBoot+MyBatis+JDBC Driver, etc.) to access the database, these ORM frameworks usually support setting the client-side timeout for SQL queries from multiple dimensions such as transactions, SQL statements, and packet forwarding. For example, Spring's transaction_timeout, MyBatis's statement_timeout, JDBC MySQL Driver's query_timeout, etc.

Essentially, most of these client-side timeout mechanisms need to execute the Kill statement to interrupt the query. In a distributed database scenario, the execution cost of the Kill statement is relatively high, and frequent execution will consume a relatively large amount of resources in the database system. Therefore, it is not recommended to use the above timeout mechanisms to connect to the database extensively.

From best practices, your application should directly use the socket_timeout parameter (network socket timeout parameter) of the JDBC URL to specify the SQL execution timeout because this parameter relies on the timeout mechanism of the TCP protocol itself, and no Kill statement behavior will be generated when the timeout is triggered. The example is as follows:

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