Connect to a database instance

Updated at:

You can connect to a PolarDB-X instance by using Data Management (DMS), the MySQL CLI, third-party clients, and application code that is compatible with the official MySQL protocol.

Before you begin

Before you connect to a PolarDB-X instance, complete the following tasks:

  • Obtain the database endpoint and port

    Go to the PolarDB for Distributed console. In the Instances, click the ID of your target instance to open its basic information page. In the Connection Information section, find the database endpoint and port.

    image

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

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

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

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

  • Create a database account.

  • Configure an instance whitelist

    Go to the PolarDB for Distributed console. In the Instances, click the ID of the target instance to go to its details page. In the left-side navigation pane, choose Configuration and Management > Security Management. Then, Configuration a whitelist or Add Whitelist. For more information, see Set a whitelist.

    image

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

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

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

      To find the public IP address of your on-premises environment, run one of the following commands:

      • On Linux, open a terminal and run the curl ifconfig.me command.

      • On Windows, open Command Prompt and run the curl ip.me command.

      • On macOS, open a terminal and run the curl ifconfig.me command.

      If your local network uses a proxy, the IP address returned by these commands may not be your actual public IP address. In this case, you can temporarily add the CIDR block 0.0.0.0/0 to the PolarDB-X instance whitelist. After connecting to the instance, run the SHOW PROCESSLIST; command to find your actual public IP address. Then, replace the CIDR block 0.0.0.0/0 in the whitelist with your actual public IP address.

      image

    • The CIDR block 0.0.0.0/0 allows access from all IP addresses and poses a significant security risk. Add it to the whitelist only when strictly necessary.

Connect to the database instance

The following sections demonstrate several ways to connect to your database instance.

DMS

Data Management (DMS) is an all-in-one graphical tool from Alibaba Cloud for managing your PolarDB-X instance. It provides comprehensive features, including data and schema management, security auditing, and performance optimization, allowing you to manage your instance without other tools.

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

    image

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

    image

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

    • After you configure the login parameters, you can click Test Connectivity in the lower-left corner. If the connection test fails, check the instance information that you entered according to the error message. For example, make sure that the account or password is correct.

    • DMS attempts to add its server IP addresses to the instance whitelist automatically. If this process fails, you must add the IP addresses manually.

  3. After you log on, you can find the PolarDB-X instance in the Instances Connected list in the left-side navigation pane, ready for management.

    image

Client

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

  • MySQL Workbench (Recommended)

  • SQLyog

  • Sequel Pro

  • Navicat for MySQL

Note

Third-party GUI clients can perform basic database operations, including CRUD and DDL operations. However, advanced client-specific features may not be supported by PolarDB-X.

The following steps use MySQL Workbench 8.0.29 as an example. The steps for other clients are similar.

  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<username> -p<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.

  • This parameter is optional if the default port is used.

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 are prompted to enter the password after the Enter password message appears.

  • If you specify 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 connect.

Note

This parameter is optional.

test_db

Application

Connecting to a PolarDB-X instance is the same as connecting to other MySQL databases. You only need to replace the database endpoint, port, username, and password. The following examples show how to access a PolarDB database from an application by using different programming languages:

Java

This example shows how to use the MySQL JDBC driver in a Maven project to connect to a PolarDB-X instance.

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

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

Python

This example shows how to use the PyMySQL library in Python 3 to connect to a PolarDB-X instance.

  1. Install the PyMySQL library. If you have not installed it, run 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
    
    # Connection settings
    host = '<HOST>'  # PolarDB-X instance endpoint
    port = 3306  # Default port is 3306.
    user = '<USER>'  # Database account
    password = '<PASSWORD>'  # Password for the database account
    database = '<DATABASE>'  # Target database
    
    try:
        # Create a connection.
        connection = pymysql.connect(
            host=host,
            port=port,
            user=user,
            passwd=password,
            db=database
        )
    
        # Create a cursor.
        with connection.cursor() as cursor:
            # Run a query.
            sql = "SELECT * FROM `<YOUR_TABLE_NAME>`"  # Table to query
            cursor.execute(sql)
    
            # Read results.
            results = cursor.fetchall()
            for row in results:
                print(row)
    
    finally:
        # Close the connection.
        if 'connection' in locals() and connection.open:
            connection.close()
    

Go

This example shows how to use the database/sql package and the go-sql-driver/mysql driver in Go 1.23.0 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() {
        // Connection settings
        dbHost := "<HOST>"       // PolarDB-X instance endpoint
        dbPort := "3306"         // Default port is 3306.
        dbUser := "<USER>"       // Database account
        dbPass := "<PASSWORD>"   // Password for the database account
        dbName := "<DATABASE>"   // Target database
    
        // 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 connection.
        db, err := sql.Open("mysql", dsn)
        if err != nil {
            log.Fatalf("Failed to connect to database: %v", err)
        }
        defer db.Close()
    
        // Verify the connection.
        err = db.Ping()
        if err != nil {
            log.Fatalf("Failed to ping database: %v", err)
        }
    
        // Create a cursor-like query.
        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 a 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()
    
        // Read 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 iteration errors.
        if err := rows.Err(); err != nil {
            log.Fatalf("Error during iteration: %v", err)
        }
    }
    

FAQ

Cannot connect from an ECS instance

Troubleshoot the issue by performing the following steps:

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

  2. Verify that the database endpoint and port and the account and password are correct.

  3. Test the network connection from the ECS instance by running ping <database_endpoint> or telnet <database_endpoint> <port>.

  4. If you use a Internal Network 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 Network 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 connect the VPCs. For more information, see Connect VPCs in the same region.

    2. Verify that the private IP address or CIDR block of the ECS instance is in the whitelist of the PolarDB-X instance. For more information, see Set an instance whitelist.

  5. If you use a Internet endpoint, verify that the public IP address of the ECS instance is in the whitelist of the PolarDB-X instance. For more information, see Set an instance whitelist.

Note

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

Cannot connect from on-premises

Troubleshoot the issue by performing the following steps:

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

  2. Verify that the database endpoint and port and the account and password are correct.

    Note

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

  3. Test the network connection from your on-premises environment by running ping <database_endpoint> or telnet <database_endpoint> <port>.

  4. Verify that the public IP address or CIDR block of your on-premises environment is in the whitelist of the PolarDB-X instance. For more information, see Set an instance whitelist.

    To find the public IP address of your on-premises environment, run one of the following commands:

    • On Linux, open a terminal and run the curl ifconfig.me command.

    • On Windows, open Command Prompt and run the curl ip.me command.

    • On macOS, open a terminal and run the curl ifconfig.me command.

    If your local network uses a proxy, the IP address returned by these commands may not be your actual public IP address. In this case, you can temporarily add the CIDR block 0.0.0.0/0 to the PolarDB-X instance whitelist. After connecting to the instance, run the SHOW PROCESSLIST; command to find your actual public IP address. Then, replace the CIDR block 0.0.0.0/0 in the whitelist with your actual public IP address.

    image

Error: Access denied

This error indicates an incorrect database account or password. Verify your credentials. You can manage your account and reset your password in the PolarDB for Distributed console by choosing Configuration and Management > Accounts to manage your database account and password.

Error: Unknown host

This error means the database endpoint is incorrect. Verify that you have entered the correct endpoint, which should be in the format pxc-xxx.polarx.rds.aliyuncs.com. You can find the correct endpoint in the PolarDB for Distributed console in the Basic Information > Connection Information section.

Error: Connection timeout

This error typically means the IP address of your environment is not correctly configured in the PolarDB-X instance's whitelist. Ensure your public IP address or CIDR block is added and is correct.

To find the public IP address of your on-premises environment, run one of the following commands:

  • On Linux, open a terminal and run the curl ifconfig.me command.

  • On Windows, open Command Prompt and run the curl ip.me command.

  • On macOS, open a terminal and run the curl ifconfig.me command.

If your local network uses a proxy, the IP address returned by these commands may not be your actual public IP address. In this case, you can temporarily add the CIDR block 0.0.0.0/0 to the PolarDB-X instance whitelist. After connecting to the instance, run the SHOW PROCESSLIST; command to find your actual public IP address. Then, replace the CIDR block 0.0.0.0/0 in the whitelist with your actual public IP address.

image

Timeout best practices

If your application uses a common Object-Relational Mapping (ORM) framework, such as Spring Boot, MyBatis, or a JDBC driver, to access the database, these frameworks usually allow you to set client-side timeouts for SQL queries at different levels, such as at the transaction or statement level.

Most of these client-side timeout mechanisms interrupt queries by issuing a KILL command to the database. In a distributed database like PolarDB-X, KILL operations are expensive. Therefore, we recommend avoiding heavy reliance on these types of timeouts.

For best performance, use the socketTimeout parameter in the JDBC URL to control SQL execution timeout. This method uses the TCP protocol's native timeout mechanism and avoids sending costly KILL commands. 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>