Python中的数据连接池


python中可以使用pymysql进行数据库连接以及增删改查的操作,但是每次连接mysql请求时,都是独立访问请求,比较浪费资源,而且如果访问量比较大的话,对mysql性能影响也比较大,所以在实际中,通常会使用数据库连接池技术来访问数据库,达到资源复用

创建数据库连接池:

 1 import time
 2 import pymysql
 3 import threading
 4 from DBUtils.PooledDB import PooledDB, SharedDBConnection
 5 POOL = PooledDB(
 6     creator=pymysql,  # 使用链接数据库的模块
 7     maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数
 8     mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
 9     maxcached=5,  # 链接池中最多闲置的链接,0和None不限制
10     maxshared=3,  # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
11     blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
12     maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制
13     setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
14     ping=0,
15     # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
16     host='127.0.0.1',
17     port=3306,
18     user='root',
19     password='123',
20     database='pooldb',
21     charset='utf8'
22 )

使用连接池:

 1 from dbpool import POOL  # 导入我们创建的数据库连接池包
 2 import pymysql
 3 
 4 
 5 # 打开连接
 6 def create_conn():
 7     conn = POOL.connection()
 8     cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
 9 
10     return conn,cursor
11 
12 
13 # 关闭连接
14 def close_conn(conn,cursor):
15     cursor.close()
16     conn.close()
17 
18 
19 # 插入一条数据
20 def insert(sql,args):
21     conn,cursor = create_conn()
22     res = cursor.execute(sql,args)
23     conn.commit()
24     close_conn(conn,cursor)
25     return res
26 
27 
28 # 查询一条数据
29 def fetch_one(sql,args):
30     conn,cursor = create_conn()
31     cursor.execute(sql,args)
32     res = cursor.fetchone()
33     close_conn(conn,cursor)
34     return res
35 
36 
37 # 查询所有数据
38 def fetch_all(sql,args):
39     conn,cursor = create_conn()
40     cursor.execute(sql,args)
41     res = cursor.fetchall()
42     close_conn(conn,cursor)
43     return res
44 
45 
46 # sql = "insert into users(name,age) VALUES (%s, %s)"
47 
48 # insert(sql,("mjj",9))
49 
50 sql = "select * from users where name=%s and age=%s"  # sql语句
51 
52 print(fetch_one(sql,("mjj",9))) # 打印结果

使用连接池:

 1 def func():
 2     # 检测当前正在运行连接数的是否小于最大链接数,如果不小于则:等待或报raise TooManyConnections异常
 3     # 否则
 4     # 则优先去初始化时创建的链接中获取链接 SteadyDBConnection。
 5     # 然后将SteadyDBConnection对象封装到PooledDedicatedDBConnection中并返回。
 6     # 如果最开始创建的链接没有链接,则去创建一个SteadyDBConnection对象,再封装到PooledDedicatedDBConnection中并返回。
 7     # 一旦关闭链接后,连接就返回到连接池让后续线程继续使用。
 8     conn = POOL.connection()
 9 
10     cursor = conn.cursor()
11     cursor.execute('select * from tb1')
12     result = cursor.fetchall()
13     conn.close()
14 
15 使用数据库连接池中的链接
View Code

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM