python多线程操作pymysql

python多线程操作pymysql需要加锁
参考代码如下:

import pymysql
from threading import *
lock = Lock()
db = pymysql.connect(
    host='127.0.0.1',
    user='root',
    password='root',
    database='test1',
    port=3306
)

def write():
    print("线程{}执行".format(current_thread().getName()))
    cursor = db.cursor()
    try:
        lock.acquire()
        cursor.execute("insert into user values('alex',22,'2001-04-17')")
        db.commit()
        lock.release()
    except:
        db.rollback()

def read():
    print("线程{}执行".format(current_thread().getName()))
    lock.acquire()
    cursor = db.cursor()
    cursor.execute("select * from user")
    data = cursor.fetchall()
    print("所有数据:", data)
    lock.release()
t1 = Thread(target=write)
t2 = Thread(target=read)
t1.start()
t2.start()

你可能感兴趣的:(笔记,python,数据库)