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