MySQL Connector/Python 开发者指南  /  Connector/Python 代码示例  /  使用 Connector/Python 连接到 MySQL

5.1 使用 Connector/Python 连接到 MySQL

connect() 构造函数创建一个到 MySQL 服务器的连接,并返回一个 MySQLConnection 对象。

以下示例演示如何连接到 MySQL 服务器

Press CTRL+C to copy
import mysql.connector cnx = mysql.connector.connect(user='scott', password='password', host='127.0.0.1', database='employees') cnx.close()

第 7.1 节 “Connector/Python 连接参数” 描述了允许的连接参数。

也可以使用 connection.MySQLConnection() 类创建连接对象

Press CTRL+C to copy
from mysql.connector import (connection) cnx = connection.MySQLConnection(user='scott', password='password', host='127.0.0.1', database='employees') cnx.close()

这两种形式(使用 connect() 构造函数或直接使用类)都是有效的,功能上也相同,但建议使用 connect(),并且本手册中的大多数示例都使用它。

要处理连接错误,请使用 try 语句并使用 errors.Error 异常捕获所有错误

Press CTRL+C to copy
import mysql.connector from mysql.connector import errorcode try: cnx = mysql.connector.connect(user='scott', database='employ') except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") else: print(err) else: cnx.close()

在字典中定义连接参数并使用 ** 运算符是另一种选择

Press CTRL+C to copy
import mysql.connector config = { 'user': 'scott', 'password': 'password', 'host': '127.0.0.1', 'database': 'employees', 'raise_on_warnings': True } cnx = mysql.connector.connect(**config) cnx.close()

定义 Logger 选项、重新连接例程,并定义为名为 connect_to_mysql 的连接方法

Press CTRL+C to copy
import logging import time import mysql.connector # Set up logger logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") # Log to console handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) # Also log to a file file_handler = logging.FileHandler("cpy-errors.log") file_handler.setFormatter(formatter) logger.addHandler(file_handler) def connect_to_mysql(config, attempts=3, delay=2): attempt = 1 # Implement a reconnection routine while attempt < attempts + 1: try: return mysql.connector.connect(**config) except (mysql.connector.Error, IOError) as err: if (attempts is attempt): # Attempts to reconnect failed; returning None logger.info("Failed to connect, exiting without a connection: %s", err) return None logger.info( "Connection failed: %s. Retrying (%d/%d)...", err, attempt, attempts-1, ) # progressive reconnect delay time.sleep(delay ** attempt) attempt += 1 return None

使用上述例程连接和使用 Sakila 数据库,假设它定义在一个名为 myconnection.py 的文件中

Press CTRL+C to copy
from myconnection import connect_to_mysql config = { "host": "127.0.0.1", "user": "user", "password": "pass", "database": "sakila", } cnx = connect_to_mysql(config, attempts=3) if cnx and cnx.is_connected(): with cnx.cursor() as cursor: result = cursor.execute("SELECT * FROM actor LIMIT 5") rows = cursor.fetchall() for rows in rows: print(rows) cnx.close() else: print("Could not connect")

使用 Connector/Python Python 或 C 扩展

Connector/Python 提供了两种实现:纯 Python 接口和使用 MySQL C 客户端库的 C 扩展(请参阅 第 8 章 “Connector/Python C 扩展”)。这可以在运行时使用 use_pure 连接参数进行配置。从 MySQL 8 开始,它默认为 False,这意味着使用 C 扩展。如果系统上没有 C 扩展,则 use_pure 默认为 True。设置 use_pure=False 会导致连接使用 C 扩展(如果您的 Connector/Python 安装包含它),而 use_pure=True 表示使用 Python 实现(如果可用)。

注意

use_pure 选项和 C 扩展是在 Connector/Python 2.1.1 中添加的。

以下示例演示如何将 use_pure 设置为 False。

Press CTRL+C to copy
import mysql.connector cnx = mysql.connector.connect(user='scott', password='password', host='127.0.0.1', database='employees', use_pure=False) cnx.close()

也可以通过导入 _mysql_connector 模块而不是 mysql.connector 模块来直接使用 C 扩展。有关更多信息,请参阅 第 8.2 节 “_mysql_connector C 扩展模块”