Guo*_*Liu 5 python mysql multithreading
PyMySQL,一个用于访问 MySQL 数据库的 python 包,似乎不支持 SELECT ... FOR UPDATE。
在下面的代码中,我使用 SELECT...FOR UPDATE 读取函数 f() 中的 some_table,使用 UPDATE 修改 g() 中的表,并为每个函数生成 50 个线程。
我预计会发生死锁,因为 SELECT...FOR UPDATE 应该阻止 g 生成的线程。但实际上并没有发生僵局。有人可以解释一下为什么吗?
from threading import Thread
import pymysql
def f():
db = pymysql.connect("localhost", "tester","pwd", "testDB")
cur = db.cursor()
sql = "SELECT * FROM some_table FOR UPDATE"
try:
cur.execute(sql)
except:
print("Exception in select")
def g():
db = pymysql.connect("localhost", "tester", "pwd","testDB")
cur = db.cursor()
sql = "UPDATE some_table SET val=20 WHERE id=2"
try:
cur.execute(sql)
db.commit()
except:
print("Exception in update")
db.rollback()
for _ in range(50):
Thread(target=f, args=()).start()
Thread(target=g, args=()).start()
Run Code Online (Sandbox Code Playgroud)
我正在使用 Python 3.4 和 PyMySQL 0.6.6。先感谢您。
PyMySQL 确实支持SELECT ... FOR UPDATE
但您需要使用以下方式开始交易connection.begin()
这是一个例子:
connection= pymysql.connect("localhost", "tester", "pwd","testDB")
connection.begin()
cursor = db.cursor()
cursor.execute("SELECT * FROM some_table FOR UPDATE")
Run Code Online (Sandbox Code Playgroud)
表/行(取决于您的选择查询)现在处于锁定状态。只有当前连接才能进行更改。
来释放锁。你可以,
connection.commit()
Run Code Online (Sandbox Code Playgroud)
connection.close()
Run Code Online (Sandbox Code Playgroud)