Use the mysqlclient library to connect to an AnalyticDB for MySQL cluster, run SQL statements, and retrieve results.
Prerequisites
Before you begin, make sure you have:
Python 3
The
mysqlclientlibrary installed:mysqlclientis the Python 3 package name. It is imported asMySQLdbin code.pip install mysqlclientAn AnalyticDB for MySQL cluster with a database and an account (privileged or standard)
Connect to the cluster
The following example establishes a connection, runs a query to retrieve the database version, and closes the connection.
import MySQLdb
# Open a connection to the cluster.
db = MySQLdb.connect(
host="<endpoint>", # Cluster endpoint or IP address
port=3306, # Port number
user="<account-name>", # Privileged or standard account
passwd="<password>", # Account password
db="<db-name>" # Target database name
)
cursor = db.cursor()
# Execute a SQL statement.
cursor.execute("SELECT VERSION()")
# Fetch the result.
data = cursor.fetchone()
print("Database version: %s" % data)
# Close the connection.
db.close()Replace the placeholders before running the code:
| Placeholder | Description | Example |
|---|---|---|
<endpoint> | Endpoint or IP address of the cluster | am-bp***.ads.aliyuncs.com |
<account-name> | Name of the account used to connect | myaccount |
<password> | Password of the account | — |
<db-name> | Name of the target database | mydb |
AnalyticDB for MySQL supports two account types: privileged accounts and standard accounts. Both can connect using the method shown above.
Handle connection errors
Wrap the connection in a try/except block to catch and diagnose failures:
import MySQLdb
db = None
try:
db = MySQLdb.connect(
host="<endpoint>",
port=3306,
user="<account-name>",
passwd="<password>",
db="<db-name>"
)
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print("Database version: %s" % data)
except MySQLdb.Error as e:
print("Connection failed: %s" % str(e))
finally:
if db is not None:
db.close()