Connect to a database

Updated at:

You can connect to a PolarDB-X instance by using Data Management (DMS), the MySQL command-line interface (CLI), third-party clients, or applications that are compatible with the official MySQL protocol.

Prerequisites

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

  • Get the database endpoint and port

    Go to the PolarDB for Distributed console. On the Instances page, click the ID of the target instance. On the Basic Information page, find the database endpoint and port in the Connection Information section.

    image

    Note
    • Choose a Intranet or External network endpoint based on your access environment.

      • If you use an ECS instance to access PolarDB-X, and the ECS instance and the PolarDB-X instance are in the same VPC, select Internal Network. This configuration allows PolarDB-X to deliver its best performance.

      • If you access a PolarDB-X instance from an on-premises environment, use the Internet. To get a public endpoint, click Apply for Public IP Address. A Internet endpoint provides access over the Internet but will not provide optimal performance for the PolarDB-X instance.

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

  • Create a database account.

  • Configure an IP whitelist for the instance

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

    image

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

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

    • If you access PolarDB-X 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:

      • Linux: Open a terminal and run curl ifconfig.me.

      • Windows: Open Command Prompt and run curl ip.me.

      • macOS: Open a terminal and run curl ifconfig.me.

      If your on-premises network is behind a proxy, these commands may not return your actual public IP address. You can temporarily add the CIDR block 0.0.0.0/0 to the IP whitelist of the PolarDB-X instance. After you connect to the instance, run the SHOW PROCESSLIST; command to get the actual public IP address. Then, add the actual public IP address to the whitelist and remove 0.0.0.0/0.

      image

    • The CIDR block 0.0.0.0/0 allows access from all sources, which poses a high security risk. Do not add this CIDR block to the IP whitelist unless necessary.

Connect to the database

You can connect to your database instance using various methods. Choose the one that best suits your workload. The following sections demonstrate common connection methods:

Connect with DMS

Data Management (DMS) is a browser-based data management tool provided by Alibaba Cloud. It integrates various services, including data management, schema management, user authorization, security audit, data trending, data tracking, BI charts, performance optimization, and server management. You can use DMS to manage your PolarDB-X instance without using other tools.

  1. In the PolarDB for Distributed console, on the Instances page, click the ID of the 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 the PolarDB-X instance, and then click Search.

    image

    Note
    • The first time you log on to a database using DMS, it defaults to the Flexible Management control mode. After you log on, you can change the control mode by editing the instance. For more information, see Modify instance information and Control modes.

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

    • The system automatically adds the IP addresses of the DMS servers to the IP whitelist of the cloud database. If this process fails, you must add them manually.

  3. After logging on, the connected PolarDB-X instance appears in the Instances Connected section on the left, where you can begin managing it.

    image

Connect with a GUI client

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

  • MySQL Workbench (recommended)

  • SQLyog

  • Sequel Pro

  • Navicat for MySQL

Note

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

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

  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 of the database endpoint.

    Note

    The default port is 3306.

    3306

    Username

    The database account.

    polardb_x_user

    Password

    The password of the database account.

    Pass***233

Connect with the MySQL CLI

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

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

Flag

Description

Example

-h

The database endpoint.

pxc-xxx.polarx.rds.aliyuncs.com

-P

The port number of 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 of the database account.

Note

This parameter is required.

  • If you omit this parameter, the client prompts you to enter the password after Enter password 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

Connect with an application

Connecting to a PolarDB-X instance is the same as connecting to any other MySQL database. Simply use the database endpoint, port, account, and password for the instance in your client library's connection string. The following examples show how to access a PolarDB-X database from common programming languages:

Java

This example uses a Maven project and the MySQL JDBC driver 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 <HOST>, the port number, <USER>, <PASSWORD>, <DATABASE>, <YOUR_TABLE_NAME>, and <YOUR_TABLE_COLUMN_NAME> with your actual information.

    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) {
          // The endpoint, port, and name of the PolarDB-X instance.
          String url = "jdbc:mysql://<HOST>:3306/<DATABASE>?useSSL=false&serverTimezone=UTC";
          // The database account.
          String user = "<USER>";
          // The 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();
             // The data table to be queried.
             ResultSet rs = stmt.executeQuery("SELECT * FROM `<YOUR_TABLE_NAME>`");
    
             while(rs.next()) {
                // The column to be retrieved.
                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 and the PyMySQL library to connect to a PolarDB-X instance.

  1. Install the PyMySQL library.

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

    import pymysql
    
    # Database connection parameters
    host = '<HOST>'  # The endpoint of the PolarDB-X instance.
    port = 3306  # The default port is 3306.
    user = '<USER>'  # The database account.
    password = '<PASSWORD>'  # The password of the database account.
    database = '<DATABASE>'  # The name of the database to which you want to connect.
    
    try:
        # Create a database connection.
        connection = pymysql.connect(
            host=host,
            port=port,
            user=user,
            passwd=password,
            db=database
        )
    
        # Get a cursor.
        with connection.cursor() as cursor:
            # Execute an SQL query.
            sql = "SELECT * FROM `<YOUR_TABLE_NAME>`"  # The data table to be queried.
            cursor.execute(sql)
    
            # Fetch the 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.22, the database/sql package, and the go-sql-driver/mysql driver to connect to a PolarDB-X instance.

  1. Install the go-sql-driver/mysql driver.

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

    package main
    
    import (
        "database/sql"
        "fmt"
        "log"
        _ "github.com/go-sql-driver/mysql"
    )
    
    func main() {
        // Database connection parameters
        dbHost := "<HOST>"       // The endpoint of the PolarDB-X instance.
        dbPort := "3306"         // The default port is 3306.
        dbUser := "<USER>"       // The database account.
        dbPass := "<PASSWORD>"   // The password of the database account.
        dbName := "<DATABASE>"   // The name of the database to which you want to connect.
    
        // 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)
    
        // Open a 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)
        }
    
        // Query the database 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)
    
        // Execute an SQL query.
        rows, err := db.Query("SELECT * FROM `<YOUR_TABLE_NAME>`") // The data table to be queried.
        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 iteration errors.
        if err := rows.Err(); err != nil {
            log.Fatalf("Error during iteration: %v", err)
        }
    }
    

FAQ

Cannot connect from ECS to a PolarDB-X instance

To troubleshoot this issue, perform the following checks:

  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. Check the network connectivity. On the ECS instance, run the ping <database endpoint> or telnet <database endpoint> <port> command.

  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 the Internal Network endpoint. You can use one of the following methods 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 enable communication between the 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 IP whitelist of the PolarDB-X instance. For more information, see Configure an IP whitelist for the instance.

  5. If you use a Internet endpoint, check whether the public IP address of the ECS instance is added to the IP whitelist of the PolarDB-X instance. For more information, see Configure an IP whitelist for the instance.

Note

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

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

To troubleshoot this issue, perform the following checks:

  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 endpoint. If you use an ECS instance that is in the same VPC as the PolarDB-X instance, you can use a Internal Network endpoint.

  3. Check the network connectivity. In your on-premises environment, run the ping <database endpoint> or telnet <database endpoint> <port> command to test the network connectivity.

  4. Check whether the public IP address or CIDR block of your on-premises environment is added to the IP whitelist of the PolarDB-X instance. For more information, see Configure an IP whitelist for the instance.

    To find the public IP address of your on-premises environment:

    • Linux: Open a terminal and run curl ifconfig.me.

    • Windows: Open Command Prompt and run curl ip.me.

    • macOS: Open a terminal and run curl ifconfig.me.

    If your on-premises network is behind a proxy, these commands may not return your actual public IP address. You can temporarily add the CIDR block 0.0.0.0/0 to the IP whitelist of the PolarDB-X instance. After you connect to the instance, run the SHOW PROCESSLIST; command to get the actual public IP address. Then, add the actual public IP address to the whitelist and remove 0.0.0.0/0.

    image

Cannot connect to a PolarDB-X instance, and the following error is reported: Access denied for user 'xxx'@'xxx' (using password: YES)

This error indicates an incorrect database account or password. Double-check your credentials. You can go to the PolarDB for Distributed console and choose Configuration and Management > Accounts to manage the database account and password.

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

The database endpoint is incorrect. Ensure the endpoint uses the pxc-xxx.polarx.rds.aliyuncs.com format. You can go to the PolarDB for Distributed console and choose Basic Information > Connection Information to manage your database endpoint.

Failed to connect to a PolarDB-X instance with the error: Can't connect to MySQL server on 'xxx' or Connection timed out

This error typically occurs if your environment's public IP address is not added to the IP whitelist of the PolarDB-X instance, or if the whitelisted IP address is incorrect.

To find the public IP address of your on-premises environment:

  • Linux: Open a terminal and run curl ifconfig.me.

  • Windows: Open Command Prompt and run curl ip.me.

  • macOS: Open a terminal and run curl ifconfig.me.

If your on-premises network is behind a proxy, these commands may not return your actual public IP address. You can temporarily add the CIDR block 0.0.0.0/0 to the IP whitelist of the PolarDB-X instance. After you connect to the instance, run the SHOW PROCESSLIST; command to get the actual public IP address. Then, add the actual public IP address to the whitelist and remove 0.0.0.0/0.

image

Database timeout best practices

If your application uses a common ORM framework, such as Spring Boot, MyBatis, or a JDBC driver, to access the database, the framework usually allows you to set the client-side timeout period for SQL queries from multiple dimensions, such as transactions, SQL statements, and network packets. Examples include transaction_timeout in Spring, statement_timeout in MyBatis, and query_timeout in the JDBC MySQL driver.

Essentially, most of these client-side timeout mechanisms terminate queries by executing a database Kill statement. In distributed database scenarios, the Kill statement is resource-intensive, and frequent execution consumes a significant amount of database system resources. Therefore, extensive use of these timeout mechanisms for database connections is not recommended.

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