This topic describes how to use the Python MySQLdb module to connect to an AnalyticDB for MySQL cluster.

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# Establish a database connection. 
# host: the endpoint or IP address of the AnalyticDB for MySQL cluster to which you want to connect. 
# port: the port number of the AnalyticDB for MySQL cluster endpoint. 
# user: the account used to connect to the AnalyticDB for MySQL cluster. AnalyticDB for MySQL offers the following types of accounts: privileged accounts and standard accounts. 
# passwd: the password of the account used to connect to the AnalyticDB for MySQL cluster. 
# db: the name of the database in the AnalyticDB for MySQL cluster. 
db = MySQLdb.connect(host='am-bp***.ads.aliyuncs.com', port=3306, user='account_name', passwd='account_password', db='db_name')
# Use the cursor() method to obtain an operation cursor. 
cursor = db.cursor()
# Use the execute() method to execute SQL statements. 
cursor.execute("SELECT VERSION()")
# Use the fetchone() method to obtain a data entry. 
data = cursor.fetchone()
# The print command in this example is applicable only to Python 2. For Python 3, parentheses () are required in the print command. Example: print ("Database version : %s " % data). 
print "Database version : %s " % data
# Close the database connection. 
db.close()