All Products
Search
Document Center

:How can I connect to the apsaradb RDS for MySQL database by using Python?

Last Updated:Dec 24, 2020

Disclaimer: This article may contain information about third-party products. Such information is for reference only. Alibaba Cloud does not make any guarantee, express or implied, with respect to the performance and reliability of third-party products, as well as potential impacts of operations on the products.

Introduction

This topic describes how to use Python to connect to an apsaradb RDS for MySQL database.

Background

The standard Python database API is Python DB-API, and most Python database APIs use this standard.

Python2

To install the MySQLdb module, follow these steps:

  1. Install MySQLdb through compilation or pip.
  2. Refer to the following Python code to connect.
    import MySQLdb
    db=MySQLdb.connect(host="[$DB_Host]",port=[$DB_Port],user="[$DB_User]",passwd="[$DB_Pass]",db="[$DB_Name]")
    Note:
    • [$DB_Host]: specifies the host name or IP address of the database.
    • [$DB_Port]: database port number, which is usually 3306. Do not write it as port="3306" or port='3306' in the code because it must be an integer.
    • [$DB_User]: specifies the database user.
    • [$DB_Pass]: specifies the password used to log on to the database.
    • [$DB_Name]: specifies the database name.

Python3

To install the PyMySQL module, follow these steps:

  1. Install PyMySQL by compiling the project or running pip.
  2. Refer to the following Python code to connect.
    import pymysql.cursors
    connection = pymysql.connect(host='[$DB_Host]',
                               user='[$DB_User]',
                               password='[$DB_Pass]',
                               db='[$DB_Name]',
                                 charset='utf8mb4',
                               cursorclass=pymysql.cursors.DictCursor)

 Application scope

  • ApsaraDB for RDS