dbutils是Python的一个轻量级且通用的数据库连接池工具,特别是MySQL数据库。它维护了一个数据库连接池,这使得多个用户间的数据库连接更高效,因为它可以复用已经存在的连接而不是每次都创建新的连接。
记得下载dbutils库
pip install dbutils
import time
import pymysql
import threading
from DBUtils.PooledDB import PooledDB
# 链接地址
hostMysql = "172.0.0.1"
# 数据库端口
portMysql = 3366
# 用户名
userMysql = "name"
# 密码
passwordMysql = "pwd"
# 库名
dbMysql = "database"
# 定义连接池
poolMysql = PooledDB(creator=pymysql, # 使用链接数据库的模块
maxconnections=6, # 连接池允许的最大连接数,0和None表示不限制连接数
# mincached=2, # 初始化时,连接池中至少创建的空闲的连接,0表示不创建
# maxcached=5, # 连接池中空闲的最多连接数,0和None表示不限制
# maxshared=3, # 连接池中最多共享的连接数量,0和None表示全部共享
# blocking=True, # 连接池中如果没有可用连接后,阻塞等待,而不是报错
# maxusage=None, # 一个连接最多被重复使用的次数,None表示无限制
# setsession=[], # 开始会话前执行的命令列表
# ping=0, # ping MySQL服务端,检查服务是否可用
host=hostMysql,
port=portMysql,
user=userMysql,
password=passwordMysql,
database=dbMysql,
charset='utf8')
# select查询
def selectMysql(sqlSelect, sem=None):
# 从连接池中取出一个数据库连接
conn = poolMysql.connection()
# 创建数据库游标,用于执行SQL语句
cursor = conn.cursor()
# 定义查询结果
res = []
try:
# 执行查询操作
cursor.execute(sqlSelect)
# 写入查询结果
res = cursor.fetchall()
except Exception:
# 打印报错sql语句
print(sqlSelect)
# 等待后重新执行
time.sleep(20)
cursor.execute(sqlSelect)
res = cursor.fetchall()
finally:
# 关闭游标,释放游标占用资源
cursor.close()
# 关闭连接,实际上并不是真正的关闭,而是将连接归还给连接池,以便于后续复用
conn.close()
# 检查线程
if isinstance(sem, threading.Semaphore):
# 释放资源的访问权限
sem.release()
return res
def deleteMysql(sqlDelete, sem=None):
conn = poolMysql.connection()
cur = conn.cursor()
try:
# 执行SQL语句
cur.execute(sqlDelete)
# 提交修改
conn.commit()
except:
# 发生错误时回滚
conn.rollback()
finally:
cur.close()
conn.close()
if isinstance(sem, threading.Semaphore):
sem.release()
def updateMysql(sqlUpdate, sem=None):
conn = poolMysql.connection()
cur = conn.cursor()
try:
cur.execute(sqlUpdate)
conn.commit()
except Exception:
print(sqlUpdate)
# 发生错误时回滚
conn.rollback()
finally:
cur.close()
conn.close()
if isinstance(sem, threading.Semaphore):
sem.release()
def insertMysql(sqlInsert, sem=None):
conn = poolMysql.connection()
cur = conn.cursor()
try:
cur.execute(sqlInsert)
conn.commit()
except Exception:
# 发生错误时回滚
conn.rollback()
finally:
cur.close()
conn.close()
if isinstance(sem, threading.Semaphore):
sem.release()
def insertMysqlMany(sqlInsert, insertData, sem=None):
conn = poolMysql.connection()
cur = conn.cursor()
try:
cur.executemany(sqlInsert, insertData)
conn.commit()
except Exception:
print()
finally:
cur.close()
conn.close()
if isinstance(sem, threading.Semaphore):
sem.release()