Python driver for communicating with MySQL servers:
To install or update msgpack package with conda run:
1 conda install -c anaconda msgpack-python
update pip package:
1 python -m pip install --upgrade pip
To install this package with conda run:
1 conda install -c anaconda mysql-connector-python
To install this package with pip run:
1 pip install mysql-connector-python
使用Connector / Python连接MySQL:
该connect()构造函数创建到MySQL服务器的连接并返回一个 MySQLConnection对象。
1 import mysql.connector 2 3 cnx = mysql.connector.connect(user='root', password='password', 4 host='127.0.0.1', 5 database='world') 6 cnx.close()
也可以使用connection.MySQLConnection() 类创建连接对象 :
1 from mysql.connector import (connection) 2 3 cnx = connection.MySQLConnection(user='root', password='password', 4 host='127.0.0.1', 5 database='world') 6 cnx.close()
使用connect()构造函数或类直接使用的两种方法都是有效且功能相同的,但是connector()首选使用 并且在本手册的大多数示例中使用。
要处理连接错误,请使用该try 语句并使用errors.Error 异常捕获所有错误 :
1 import mysql.connector
2 from mysql.connector import errorcode
3
4 try:
5 cnx = mysql.connector.connect(user='root',
6 database='testt')
7 except mysql.connector.Error as err:
8 if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
9 print("Something is wrong with your user name or password")
10 elif err.errno == errorcode.ER_BAD_DB_ERROR:
11 print("Database does not exist")
12 else:
13 print(err)
14 else:
15 cnx.close()
如果你有很多连接参数,最好将它们保存在字典中并使用**运算符:
1 import mysql.connector
2
3 config = {
4 'user': 'root',
5 'password': 'password',
6 'host': '127.0.0.1',
7 'database': 'employees',
8 'raise_on_warnings': True,
9 }
10
11 cnx = mysql.connector.connect(**config)
12
13 cnx.close()
使用Connector / Python Python或C扩展
从Connector / Python 2.1.1开始,use_pure连接参数确定是使用纯Python接口连接到MySQL,还是使用MySQL C客户端库的C扩展。默认情况下False(使用纯Python实现)从MySQL 8开始,默认为True早期版本。如果系统上没有C扩展,那么 use_pure就是True。设置 use_pure以False使使用C扩展,如果你的连接器/ Python安装包括它,而设置连接use_pure到 False表示如果可用,则使用Python实现。以下示例与之前显示的其他示例类似,但包含的内容 use_pure=False。
通过在connect() 调用中命名参数来连接:
1 import mysql.connector 2 3 cnx = mysql.connector.connect(user='root', password='password', 4 host='127.0.0.1', 5 database='employees', 6 use_pure=False) 7 cnx.close()
使用参数字典连接:
1 import mysql.connector
2
3 config = {
4 'user': 'root',
5 'password': 'password',
6 'host': '127.0.0.1',
7 'database': 'employees',
8 'raise_on_warnings': True,
9 'use_pure': False,
10 }
11
12 cnx = mysql.connector.connect(**config)
13
14 cnx.close()
也可以通过导入_mysql_connector模块而不是 mysql.connector模块直接使用C Extension 。
https://dev.mysql.com/doc/connector-python/en/connector-python-reference.html
来源:https://www.cnblogs.com/htsg/p/9516576.html