python數據庫連接池


一  DBUtils的認識

首先管理數據庫連接池的包是 DBUtils,為高頻度並發的數據庫訪問提供更好的性能,可以自動管理連接對象的創建和釋放,最常用的兩個外部接口是PersistentDB 和 PooledDB,前者提供了單個線程專用的數據庫連接池,后者則是進程內所有線程共享的數據庫連接池。

 

二 DBUtils 簡介
DBUtils是一套Python數據庫連接池包,並允許對非線程安全的數據庫接口進行線程安全包裝。DBUtils來自Webware for Python。

DBUtils提供兩種外部接口:

  • PersistentDB :提供線程專用的數據庫連接,並自動管理連接。
  • PooledDB :提供線程間可共享的數據庫連接,並自動管理連接。

 

三 創建數據庫連接池

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 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()

 

五 自制sqlhelper

 1 class MySQLhelper(object):
 2     def __init__(self, host, port, dbuser, password, database):
 3         self.pool = PooledDB(
 4             creator=pymysql,  # 使用鏈接數據庫的模塊
 5             maxconnections=6,  # 連接池允許的最大連接數,0和None表示不限制連接數
 6             mincached=2,  # 初始化時,鏈接池中至少創建的空閑的鏈接,0表示不創建
 7             maxcached=5,  # 鏈接池中最多閑置的鏈接,0和None不限制
 8             maxshared=3,
 9             # 鏈接池中最多共享的鏈接數量,0和None表示全部共享。PS: 無用,因為pymysql和MySQLdb等模塊的 threadsafety都為1,所有值無論設置為多少,_maxcached永遠為0,所以永遠是所有鏈接都共享。
10             blocking=True,  # 連接池中如果沒有可用連接后,是否阻塞等待。True,等待;False,不等待然后報錯
11             maxusage=None,  # 一個鏈接最多被重復使用的次數,None表示無限制
12             setsession=[],  # 開始會話前執行的命令列表。如:["set datestyle to ...", "set time zone ..."]
13             ping=0,
14             # 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
15             host=host,
16             port=int(port),
17             user=dbuser,
18             password=password,
19             database=database,
20             charset='utf8'
21         )
22 
23     def create_conn_cursor(self):
24         conn = self.pool.connection()
25         cursor = conn.cursor(pymysql.cursors.DictCursor)
26         return conn,cursor
27 
28     def fetch_all(self, sql, args):
29         conn,cursor = self.create_conn_cursor()
30         cursor.execute(sql,args)
31         result = cursor.fetchall()
32         cursor.close()
33         conn.close()
34         return result
35 
36 
37     def insert_one(self,sql,args):
38         conn,cursor = self.create_conn_cursor()
39         res = cursor.execute(sql,args)
40         conn.commit()
41         print(res)
42         conn.close()
43         return res
44 
45     def update(self,sql,args):
46         conn,cursor = self.create_conn_cursor()
47         res = cursor.execute(sql,args)
48         conn.commit()
49         print(res)
50         conn.close()
51         return res
52 
53 
54 sqlhelper = MySQLhelper("127.0.0.1", 3306, "root", "1233121234567", "dragon")
55 
56 # sqlhelper.fetch_all("select * from user where id=%s",(1))
57 
58 # sqlhelper.insert_one("insert into user VALUES (%s,%s)",("jinwangba",4))
59 
60 # sqlhelper.update("update user SET name=%s WHERE  id=%s",("yinwangba",1))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM