构造函数创建到 MySQL 服务器的connect()
连接并返回一个
MySQLConnection
对象。
以下示例显示了如何连接到 MySQL 服务器:
Press CTRL+C to copyimport mysql.connector cnx = mysql.connector.connect(user='scott', password='password', host='127.0.0.1', database='employees') cnx.close()
第 7.1 节,“连接器/Python 连接参数”描述了允许的连接参数。
也可以使用 connection.MySQLConnection() 类创建连接对象:
Press CTRL+C to copyfrom mysql.connector import (connection) cnx = connection.MySQLConnection(user='scott', password='password', host='127.0.0.1', database='employees') cnx.close()
两种形式(使用connect()
构造函数或直接使用类)都是有效的且功能相同,但connect()
本手册中的大多数示例首选并使用 using。
要处理连接错误,请使用try
语句并使用
errors.Error
异常捕获所有错误:
Press CTRL+C to copyimport 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 copyimport 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()
使用连接器/Python Python 或 C 扩展
Connector/Python 提供两种实现:纯 Python 接口和使用 MySQL C 客户端库的 C 扩展(参见
第 8 章,连接器/Python C 扩展)。这可以在运行时使用use_pure
连接参数进行配置。它默认False
为 MySQL 8,这意味着使用 C 扩展。如果 C 扩展名在系统上不可用,则use_pure
默认为True
. 如果您的连接器/Python 安装包含 C 扩展,则设置
use_pure=False
会导致连接使用 C 扩展,而
use_pure=True
toFalse
表示如果可用则使用 Python 实现。
连接器use_pure
/Python 2.1.1 中添加了选项和 C 扩展。
以下示例显示如何设置use_pure
为 False。
Press CTRL+C to copyimport 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 扩展模块”。