import pymysql
from dbutils.pooled_db import PooledDB
class MysqlControls:
def __init__(self, host, port, user, password, database, charset='utf8mb4', mincached=1, maxconnections=200,
blocking=True, dictcursor=False):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self.charset = charset
self.mincached = mincached
self.maxconnections = maxconnections
self.blocking = blocking
self.dictcursor = dictcursor
def __enter__(self):
pool = PooledDB(creator=pymysql, mincached=self.mincached, maxconnections=self.maxconnections,
blocking=self.blocking, host=self.host, port=self.port, user=self.user,
password=self.password, database=self.database)
self.connection = pool.connection()
if self.dictcursor:
self.cursor = self.connection.cursor(cursor=pymysql.cursors.DictCursor)
else:
self.cursor = self.connection.cursor()
return self
def __exit__(self, *exc_info):
self.connection.commit()
self.cursor.close()
self.connection.close()
def sql_select(self, sql):
self.cursor.execute(sql)
return self.cursor.fetchall()
def sql_execute(self, sql, parma=None):
try:
if parma:
self.cursor.execute(sql, parma)
else:
self.cursor.execute(sql)
except Exception as e:
print(f"错误: {e}")
self.connection.rollback()
笔记:pymysql连接池
最新推荐文章于 2024-07-25 01:51:24 发布