Python使用Mysql连接池

更新时间:2023-05-15 18:20:25 阅读: 评论:0

Python使⽤Mysql连接池
0X00 为什么要⽤数据库连接池
平常可能习惯使⽤pymysql或者⼀些数据库连接包去跟数据库交互,代码可能是这样的:
import pymysql
config = {
'host': config_template['MYSQL']['HOST'],
'port': config_template['MYSQL']['PORT'],
'ur': config_template['MYSQL']['USER'],
'password': config_template['MYSQL']['PASSWD'],
'db': config_template['MYSQL']['DB'],
'chart': config_template['MYSQL']['CHARSET'],
'cursorclass': pymysql.cursors.DictCursor
}
def db_conn():
conn = t(**config)
怎么去掉色斑
矍铄cursor = conn.cursor()
return conn,cursor
⼤概就是这么个意思,将连接数据库封装为⼀个⽅法,每次需要连接的时候调⽤该⽅法获取conn和cursor对象,但是这样会有损耗,因为每次都需要 建⽴连接->执⾏数据库操作->释放连接。⽽数据库连接池为维护⼀个保存有多个数据库连接的池⼦,每次需要连接数据库时,从连接池中取出⼀个连接进⾏使⽤即可,使⽤完毕后连接不会释放,⽽是归还给连接池进⾏管理,节省了不断建⽴连接和释放连接的过程。
0X01 使⽤DBUtils建⽴数据库连接池
import pymysql
from fig import config_template
from DBUtils.PooledDB import PooledDB
class MysqlPool:
config = {
'creator': pymysql,
'host': config_template['MYSQL']['HOST'],
'port': config_template['MYSQL']['PORT'],
'ur': config_template['MYSQL']['USER'],
'password': config_template['MYSQL']['PASSWD'],special是什么意思
'db': config_template['MYSQL']['DB'],
职业规划测试
'chart': config_template['MYSQL']['CHARSET'],
'maxconnections': 70, # 连接池最⼤连接数量
'cursorclass': pymysql.cursors.DictCursorrealize过去式
}
pool = PooledDB(**config)
回眸一笑的意思
def __enter__(lf):
< = tion()我自己英语
lf.cursor = lf.conn.cursor()
return lf
def __exit__(lf, type, value, trace):
lf.cursor.clo()
可以看到,通过DBUtils,实例化⼀个PooledDB对象作为MysqlPool类的类属性,通过重写__enter__和__exit__⽅法让我们在进⼊with语句时从连接池中获取到数据库连接,在with语句结束后,⾃动释放连接池,归还给连接池。
使⽤⽅式与普通连接mysql并⽆区别,使⽤with语句调⽤即可:to be or not to be
def func(tar_id):
with MysqlPool() as db:
ute('YOUR_SQL')
装饰器⽤法:
def db_conn(func):
def wrapper(*args, **kw):
with MysqlPool() as db:
result = func(db, *args, **kw)
return result
return wrapper
@db_conn
spicedef update_info(db, *args, **kw):
try:
ute("YOUR_SQL")
return 0
constellationexcept Exception as e:
return 1
DBUtils还有很多强⼤的功能,如果有更多的需求可以⾃⾏查阅相关⽂档,本⽂仅仅是抛砖引⽟,提供⼀种数据库连接池的使⽤⽅法。

本文发布于:2023-05-15 18:20:25,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/90/109648.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:连接   数据库   释放   查阅   交互   需要   可能   色斑
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图