Python脚本使用多线程存储数据到MySQL时,为避免多线程问题,确保数据库操作的线程安全性
解决方案1:
每个线程在执行请求和存储结果之前都创建了自己的数据库连接,并在操作完成后关闭了连接。
性能问题
每个线程都创建和关闭数据库连接可能会导致性能问题。
尤其是在高并发场景下,频繁地打开和关闭连接会大大增加开销,并可能达到数据库的最大连接数限制。
这时,会考虑使用MySQL连接池 DBUtils
。
使用连接池可以显著提高性能。
连接池预先创建一定数量的数据库连接,并在多线程环境中复用这些连接。
Python中有一些库如: DBUtils.PooledDB 可以用来实现这一点。
安装DBUtils:
pip install DBUtils
导入库:DBUtils
from DBUtils.PooledDB import PooledDB # 实现 pymysql 连接池
可能会报错:
No module named 'DBUtils'
或者执行连接池,没有写入数据
pool = PooledDB(creator=pymysql, **db_config, pool_size=10)
pool 创建失败导致
原因:DBUtils版本问题,即版本不兼容。
DBUtils==1.3 版本用法:
from DBUtils.PooledDB import PooledDB # 实现 pymysql 连接池
# 创建连接池 pool_size根据需要设置
pool = PooledDB(creator=pymysql, **db_config, pool_size=10)
DBUtils==3.0.3 版本用法:
from dbutils.pooled_db import PooledDB
# maxconnections
pool = PooledDB(creator=pymysql, **db_config, maxconnections=10)
DBUtils==3.0.3 其他相关使用:
# 数据库配置
db_config = {
'host': 'your_host',
'port': 3306,
'database': 'your_database',
'user': 'your_username',
'password': 'your_password',
'charset': 'utf8mb4'
}
# 创建连接池
pool = PooledDB(
creator=pymysql, # 使用pymysql模块连接MySQL
maxconnections=10, # 连接池允许的最大连接数
**DB_CONFIG
)
update_sql = """
update tb_l set
duration=%s, title=%s
where s_id=%s
"""
# 构造更新的数据元组
update_data = (item['duration'], item['title'],
item['s_id'])
# 为当前线程创建独立的数据库连接
# connection = pymysql.connect(**db_config)
# 优化:从连接池中获取数据库连接
connection = pool.connection()
try:
# 执行插入操作
with connection.cursor() as insert_cursor:
insert_cursor.execute(update_sql, update_data)
connection.commit() # 提交事务以确保数据被写入数据库
finally:
# 确保关闭数据库连接,将连接返回到连接池
connection.close()
2024-05-29
以上。