下面是代码的详细介绍
import pymysql from DBUtils.PooledDB import PooledDB class DBUtil: # 数据库连接池配置 pool = PooledDB( creator=pymysql, # 使用pymysql模块创建连接 maxconnections=10, # 连接池中允许的最大连接数 host='localhost', # 数据库主机地址 port=3306, # 数据库端口 user='root', # 数据库用户名 password='root', # 数据库密码 database='books', # 数据库名 charset='utf8' # 字符集 )这段代码定义了一个
PooledDB
实例作为连接池,并配置了连接池的一些参数。creator
参数指定了用于创建新连接的模块(这里是pymysql
),maxconnections
是连接池中允许的最大连接数。其他参数如host
、port
、user
、password
、database
和charset
分别用于指定数据库的地址、端口、用户名、密码、数据库名和字符集。# 获取数据库连接 @classmethod def get_connection(cls): return cls.pool.connection()这个类方法用于从连接池中获取一个数据库连接。当调用
get_connection
时,连接池会尝试返回一个可用的连接。如果连接池中没有可用的连接且连接数未达到maxconnections
,连接池会创建一个新的连接并返回;否则,会等待直到有可用的连接。# 执行SQL查询 @classmethod def execute_sql(cls, sql, params=None): connection = cls.get_connection() cursor = connection.cursor() try: cursor.execute(sql, params) if sql.lower().startswith('select'): result = cursor.fetchall() return result else: connection.commit() except Exception as e: connection.rollback() raise # Reraise the exception for caller to handle finally: cursor.close() connection.close()这个类方法用于执行SQL查询。它首先通过
get_connection
方法从连接池中获取一个连接,并创建一个游标对象。然后,它尝试执行SQL语句,将参数params
作为参数传递给cursor.execute
方法,实现参数化查询,这有助于防止SQL注入。如果SQL语句是查询(以
SELECT
开头),则使用cursor.fetchall()
获取所有结果并返回。对于其他类型的SQL语句(如更新、插入或删除),执行connection.commit()
提交事务。如果在执行过程中发生异常,会执行
connection.rollback()
回滚事务,并重新抛出异常,以便调用者可以处理。无论是否发生异常,finally
块都会确保游标和连接被正确关闭,释放资源。# 示例用法 # 查询数据 result = DBUtil.execute_sql("SELECT * FROM some_table WHERE id = %s", (1,)) print(result) # 更新数据 DBUtil.execute_sql("UPDATE some_table SET name = %s WHERE id = %s", ("NewName", 1))这部分是示例用法,展示了如何使用
DBUtil
类来查询和更新数据库中的数据。通过传递SQL语句和参数给execute_sql
方法,可以执行相应的数据库操作,并获取查询结果。总的来说,优化后的代码通过引入连接池和参数化查询,提高了数据库操作的性能和安全性。连接池减少了连接创建和销毁的开销,而参数化查询则有效防止了SQL注入攻击。同时,代码也确保了资源的正确释放,避免了潜在的资源泄漏问题。
全部代码如下
import pymysql
from dbutils.pooled_db import PooledDB
class DBUtil:
# 数据库连接池配置
pool = PooledDB(
creator=pymysql, # 使用pymysql模块创建连接
maxconnections=10, # 连接池中允许的最大连接数
host='localhost', # 数据库主机地址
port=3306, # 数据库端口
user='root', # 数据库用户名
password='root', # 数据库密码
database='books', # 数据库名
charset='utf8' # 字符集
)
# 获取数据库连接
@classmethod
def get_connection(cls):
return cls.pool.connection()
# 执行SQL查询
@classmethod
def execute_sql(cls, sql, params=None):
connection = cls.get_connection()
cursor = connection.cursor()
try:
cursor.execute(sql, params)
if sql.lower().startswith('select'):
result = cursor.fetchall()
return result
else:
connection.commit()
except Exception as e:
connection.rollback()
raise # Reraise the exception for caller to handle
finally:
cursor.close()
connection.close()
# 示例用法
# 查询数据
result = DBUtil.execute_sql("SELECT * FROM some_table WHERE id = %s", (1,))
print(result)
# 更新数据
DBUtil.execute_sql("UPDATE some_table SET name = %s WHERE id = %s", ("NewName", 1))