Connect to a database
This topic describes how to connect to a PolarDB for PostgreSQL cluster.
Preparations
Before you connect to a database cluster, complete the following preparations:
After you complete the preparations, you can connect to the database cluster.
Connect to a database cluster
You can connect to a database cluster in many ways. Choose the connection method that suits your business requirements. The following are some examples of how to connect to a database cluster:
Use DMS to connect to a cluster
DMS is a graphical data management tool provided by Alibaba Cloud. It is a data management service that integrates data management, schema management, user authorization, security auditing, data trends, data tracking, BI charts, performance optimization, and server management. You can manage your PolarDB cluster directly in DMS without using other tools.
-
Go to the PolarDB console. In Clusters, click the target cluster ID to open the cluster details page. In the upper-right corner of the page, click Log on to Database.
-
In the dialog box that appears, enter the Database Account and Database Password that you created for the cluster, and then click Login.
-
After you log on, in the left-side navigation pane, choose . The PolarDB cluster that you logged on to appears in the list, where you can manage it.
Use a client to connect to a cluster
You can use any general-purpose client to connect to a PolarDB cluster. This example uses pgAdmin 4 v9.0. The procedure is similar for other clients.
-
Download and install the pgAdmin 4 client.
-
Open the pgAdmin 4 client, right-click Servers, and choose .
-
On the General tab, set the connection name. On the Connection tab, configure the information of the cluster to connect to, and click Save.
Parameter
Description
Host name/address
PolarDB cluster's database endpoint and port.
If you use an ECS instance to access the PolarDB cluster and the ECS instance is in the same VPC as the PolarDB cluster, specify the Private endpoint and port.
If you access the PolarDB cluster from an on-premises environment, specify the Public endpoint and port.
The default port is 5432.
Port
Username
PolarDB cluster's database account and password.
Password
-
View the connection result. If the connection information is correct, the following page appears, indicating that the connection is successful.
Notepostgresis the default system database. Do not perform any operations in this database.
Use the command line to connect to a cluster
You can download psql from the PostgreSQL website and use it to connect to a PolarDB database cluster. You can also use the PolarDB-provided PolarDB-Toolspsql tool in the toolkit to connect to a PolarDB database cluster.
-
The psql connection method is the same on Windows and Linux.
-
For more information about how to use psql, see the PostgreSQL psql documentation.
Syntax
psql -h <host> -p <port> -U <username> -d <dbname>
Parameter | Description |
| PolarDB cluster's database endpoint and port.
|
| |
| PolarDB cluster's database account. |
| The database that you want to manage. |
Example
psql -h pc-xxx.rwlb.rds.aliyuncs.com -p 5432 -U testusername -d postgres
Use an application to connect to a cluster
You connect to a PolarDB for PostgreSQL cluster the same way you connect to other PostgreSQL databases. You only need to replace the database endpoint, port, account, and password. The following examples show how applications in several programming languages access a PolarDB database:
Java
This example uses a Maven project and the PostgreSQL JDBC driver to connect to a PolarDB for PostgreSQL cluster.
-
First, add the PostgreSQL JDBC driver dependency to the pom.xml file. Sample code:
<dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.18</version> </dependency> -
Connect to the cluster. Replace the
<HOST>,<PORT>,<USER>,<PASSWORD>,<DATABASE>,<YOUR_TABLE_NAME>, and<YOUR_TABLE_COLUMN_NAME>parameters.import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class PolarDBConnection { public static void main(String[] args) { // Database URL, username, and password String url = "jdbc:postgresql://<HOST>:<PORT>/<DATABASE>"; String user = "<USER>"; String password = "<PASSWORD>"; try { // Load the JDBC driver Class.forName("org.postgresql.Driver"); // Establish the connection Connection conn = DriverManager.getConnection(url, user, password); // Create a Statement object Statement stmt = conn.createStatement(); // Run an SQL query ResultSet rs = stmt.executeQuery("SELECT * FROM <YOUR_TABLE_NAME>"); // Process the result set while (rs.next()) { System.out.println(rs.getString("<YOUR_TABLE_COLUMN_NAME>")); } // Close resources rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
Python
This example uses Python 3 and the psycopg2 library to connect to a PolarDB for PostgreSQL cluster.
-
First, install the psycopg2 library. If you have not installed it, run the following command:
pip3 install psycopg2-binary -
Connect to the cluster. Replace the
<HOST>,<PORT>,<USER>,<PASSWORD>,<DATABASE>, and<YOUR_TABLE_NAME>parameters.import psycopg2 try: # Connection parameters conn = psycopg2.connect( host="<HOST>", # The database host address database="<DATABASE>", # The database name user="<USER>", # The username password="<PASSWORD>", # The password port="<PORT>" # The port ) # Create a cursor object cursor = conn.cursor() # Run a query cursor.execute("SELECT * FROM <YOUR_TABLE_NAME>") # Retrieve all results records = cursor.fetchall() for record in records: print(record) except Exception as e: print("Error:", e) finally: # Close the connection if 'cursor' in locals(): cursor.close() if 'conn' in locals(): conn.close()
Go
This example uses Go 1.23.0 with the database/sql package and the lib/pq driver to connect to a PolarDB for PostgreSQL cluster.
-
First, install the
lib/pqdriver. Run the following command to install it:go get -u github.com/lib/pq -
Connect to the cluster. Replace the
<HOST>,<PORT>,<USER>,<PASSWORD>,<DATABASE>, and<YOUR_TABLE_NAME>parameters.package main import ( "database/sql" "fmt" "log" _ "github.com/lib/pq" // Initialize the driver ) func main() { // Connection string format connStr := "user=<USER> password=<PASSWORD> dbname=<DATABASE> host=<HOST> port=<PORT> sslmode=disable" // Open a database connection db, err := sql.Open("postgres", connStr) if err != nil { log.Fatal(err) } defer db.Close() // Close the connection before the program exits // Test the connection err = db.Ping() if err != nil { log.Fatal(err) } fmt.Println("Connected to PostgreSQL!") // Query execution example rows, err := db.Query("SELECT * FROM <YOUR_TABLE_NAME>") if err != nil { log.Fatal(err) } defer rows.Close() }
Use Power BI Desktop to connect to a cluster
You can use the PostgreSQL connector of Power BI Desktop to connect to a PolarDB for PostgreSQL cluster and load tables.
Before you begin, make sure that the following requirements are met:
-
Download and install Power BI Desktop on a Windows device.
-
You have obtained the database endpoint and port of the cluster, and created a business database and a database account that has access permissions on it.
-
The public egress IP address of the client has been added to the Cluster Whitelists. If the client and the cluster are in the same VPC, use the Private endpoint. If you access the cluster from an on-premises environment, use the Public endpoint.
Procedure
-
Open Power BI Desktop. On the Home tab, click Get Data > More....
-
In the Get Data dialog box, choose Database > PostgreSQL database, and click Connect.
-
In the PostgreSQL database dialog box, configure the following parameters, set Data Connectivity mode to Import, and click OK.
Parameter
Description
Server
Enter the database endpoint and port of the cluster in the format
endpoint:port, for example,pc-xxxxxx.pg.polardb.rds.aliyuncs.com:5432. Do not add thepostgresql://orjdbc:prefix. Use the port displayed in the console.Database
Enter the name of the business database to connect to. Do not use the default system database
postgresfor business operations. -
In the Authentication dialog box, select Database as the authentication type, enter the User name and Password of the database account, and click Connect. The PostgreSQL connector of Power BI uses database authentication and does not support Windows integrated authentication.
NoteIf the Encryption Support dialog box appears and SSL is not enabled for the cluster, click OK to continue connecting without encryption.
-
After the connection succeeds, select the tables to import in the Navigator. Click Load to import the data directly, or click Transform Data to clean the data in Power Query.