使用python操作mysql的时候一般都会使用如下语句:
官方示例
import pymysql.cursors
# 连接到数据库后实际上TCP的连接状态是ESTABLISHED
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
#默认不自动提交事务,所以需要手动提交
connection.commit()
with connection.cursor() as cursor:
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
在这段代码里,有一个疑惑的点是,我们现在创建了一个连接,但是实例化了多个cursor,我们可不可以使用同一个连接的同一个cursor来重复使用,代码如下
with connect.cursor() as cursor:
cursor.execute("select * from person limit 1")
print(id(cursor))
data = cursor.fetchone()
print(data)
print("=============")
cursor.execute("select * from person limit 1")
print(id(cursor))
data = cursor.fetchone()
print(data)
上面的代码,我们执行完了之后发现查询操作是可以直接使用的,并且不会产生冲突,我们通过打印cursor的地址发现是同一个cursor。
插入操作
with connect.cursor() as cursor:
for id in range(1, 100, 2):
cursor.execute("insert into test(id)values(%d)"%id)
print(id)
id += 1
cursor.execute("insert into test(id)values(%d)"%id)
time.sleep(2)
print(id)
在单进程单线程环境下依然没有问题
删除
with connect.cursor() as cursor:
for id in range(100):
# cursor.execute("insert into test(id)values(%d)" % id)
cursor.execute("delete from test where id=%s"%id)
time.sleep(5)
time.sleep(10)
也没有问题
但是有博客说多进程环境下会出现问题,我一直想重现,但是没有成功,等以后重现了再来更新。
但是
- 创建了一个 cursor 以后,建议完成一个事务就 commit 一下,不要一直用它,这样一直使用,并不会和数据库完成数据同步,如果操作太多,提交的时候会超时,造成部分数据更新,部分数据丢失,数据不一致且效率低。
并且握着 cursor 期间,数据库端发生改变,也没法和客户端同步。
参考链接:
Python 数据库的Connection、Cursor两大对象
PyMySQL 0.9.2
python - 在 python MySQLdb模块中,是否应该重用游标
网友评论