最近需要做一个频繁操作数据库的应用,如果频繁的建立、关闭连接则会浪费很大部分资源,于是在网上搜索连接池的用法,如下:
首先Python3中操作数据库需要用到的库为pymysql,下载命令
pip install pymysql
简单的mysql操作
import pymysql
if __name__== "__main__":
db = pymysql.connect(host="数据库地址", user="testuser", password="test123",database="TESTDB",charset="utf8")
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
cursor.close()
db.close()
连接池的操作
import pymysql
from dbutils.pooled_db import PooledDB
if __name__== "__main__":
config = {
'creator': pymysql,
'host': "数据库地址",
'port': 3306,
'user': "testuser",
'password': "test123",
'db': "TESTDB",
'charset': 'utf8',
'maxconnections': 70, # 连接池最大连接数量
'cursorclass': pymysql.cursors.DictCursor
}
pool = PooledDB(**config)
conn = pool.connection()
cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
cursor.close()
conn.close()
如此就可以使用连接池建立连接了,
注意:此处的conn.close()并非真正的关闭连接,而是将连接返回给连接池。所以消耗的资源更小。
虽然这样代码就完成了,但是在实际应用场景中肯定是会做各种查询和插入的,那么多条语句每次都要关闭和重新建立连接是否太麻烦了呢。
问题总能解决的,只要使用装饰器就能解决这个问题
使用装饰器完善连接池
import pymysql
from dbutils.pooled_db import PooledDB
class MysqlPool:
config = {
'creator': pymysql,
'host': "数据库地址",
'port': 3306,
'user': "testuser",
'password': "test123",
'db': "TESTDB",
'charset': 'utf8',
'maxconnections': 70, # 连接池最大连接数量
'cursorclass': pymysql.cursors.DictCursor
}
pool = PooledDB(**config)
def __enter__(self):
self.conn = MysqlPool.pool.connection()
self.cursor = self.conn.cursor()
return self
def __exit__(self, type, value, trace):
self.cursor.close()
self.conn.close()
def db_conn(func):
def wrapper(*args, **kw):
with MysqlPool() as db:
result = func(db, *args, **kw)
return result
return wrapper
# 实际应用的地方
class Mysql_Db_Manage:
"""table: register_phone"""
@staticmethod
@db_conn
def select_All_Register_Phone(db):
q = "SELECT xxx FROM xxx"
db.cursor.execute(q)
result = db.cursor.fetchall()
return result