参考文档:
https://dev.mysql.com/doc/connector-python/en/
http://mysql-python.sourceforge.net/MySQLdb.html
安装方法
支持python3
的mysql driver
有mysqlclient
和pymysql
,不推荐只支持2的MySQLdb
|
|
数据库的连接
这里有所有的连接参数列表
|
|
Difference:两个库的区别
# MySQL Connector/Python
Oracle官方的实现,底层完全用C来实现
默认未开启cursorbuffer,如果需要则显式开启:cnx.cursor(buffered=True)或者mysql.connector.connect(buffered=True),开启了buffer,可同时使用多个游标
# MySQLdb
不完全用C
默认开启了cursor的,会缓存结果,但是针对特别大的查询,可能会导致程序崩溃
CURD操作
插入
# 插入一条数据
insert_stmt = (
"INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
"VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)
# 同时插入多条数据
data = [
('a', 'b', 'c', 'd'),
('e', 'f', 'g', 'h')
]
stmt = 'INSERT INTO table_name (field_name1, field_name2)' 'VALUES(%s, %s)'
cursor.executemany(stmt, data)
读取
|
|
TroubleShooting
获取insert后的ID值
1db.insert_id() # 表示上一次插入数据的ID获取原始SQL语句
1print(cursor._last_executed)多线程的情况下,出现错误”OperationalError:(2013, ‘Lost connection to MySQL server during query’)”,出现这种情况是因为在多线程的情况下,如果只有一个mysql连接,那么mysql该连接会在执行完一个线程后销毁,需要加锁,在线程里面修改全局变量,会导致该变量的引用出错
12345LOCK.acquire()mysql.cursor.execute(sql)result = mysql.cursor.fetchall()LOCK.release()print(len(result))Can’t connect to local mySQL server ough socket ‘/tmp/mysql.sock
可能原因是由于MySQL是编译安装的,没有放在默认的目录,导致python找不到默认的sock文件,可以用一个软连接将实际文件链接到这个默认的目录下面