#使用全局conn可能时间长了会造成错误。
import pymysql
import threading
# 创建全局锁对象
db_lock = threading.Lock()
# 打开数据库连接的函数
def open_database():
conn = pymysql.connect(host='localhost', user='username', password='password', database='database_name')
return conn
# 关闭数据库连接的函数
def close_database(conn):
conn.close()
# 在线程中执行数据库操作的函数
def thread_function():
# 获取全局锁
db_lock.acquire()
try:
# 打开数据库连接
conn = open_database()
# 执行数据库操作
cursor = conn.cursor()
cursor.execute("SELECT * FROM table_name")
rows = cursor.fetchall()
for row in rows:
print(row)
finally:
# 关闭数据库连接
close_database(conn)
# 释放全局锁
db_lock.release()
# 创建多个线程并启动
for i in range(5):
thread = threading.Thread(target=thread_function)
thread.start()