天天看點

python資料庫連接配接池_Python資料庫連接配接池 -元件 DBUtils

DBUtils是Python的一個用于實作資料庫連接配接池的子產品

此連接配接池有兩種連接配接模式:

DBUtils提供兩種外部接口:

PersistentDB :提供線程專用的資料庫連接配接,并自動管理連接配接。

PooledDB :提供線程間可共享的資料庫連接配接,并自動管理連接配接。

PersistentDB 模式

為每個線程建立一個連接配接,線程即使調用了close方法,也不會關閉,隻是把連結重新放到連結池,供自己線程再次使用,當線程終止時,連結自動關閉

from DBUtils.PersistentDB import PersistentDB

import pymysql

POOL = PersistentDB(

creator=pymysql, # 使用連結資料庫的子產品

maxusage=None, # 一個連結最多被重複使用的次數,None表示無限制

setsession=[], # 開始會話前執行的指令清單。

ping=0,

# ping MySQL服務端,檢查是否服務可用。

closeable=False,

# 如果為False時, conn.close() 實際上被忽略,供下次使用,再線程關閉時,才會自動關閉連結。如果為True時, conn.close()則關閉連結,那麼再次調用pool.connection時就會報錯,因為已經真的關閉了連接配接(pool.steady_connection()可以擷取一個新的連結)

threadlocal=None, # 本線程獨享值得對象,用于儲存連結對象,如果連結對象被重置

host='127.0.0.1',

port=3306,

user='root',

password='123456',

database='test',

charset='utf8'

)

def func():

conn = POOL.connection(shareable=False)

cursor = conn.cursor()

cursor.execute('select * from user')

result = cursor.fetchall()

print(result)

cursor.close()

conn.close()

if __name__ == '__main__':

func()

PooledDB 模式

建立一批連接配接到連接配接池,供所有線程共享使用。

import pymysql

from DBUtils.PooledDB import PooledDB

POOL = PooledDB(

creator=pymysql, # 使用連結資料庫的子產品

maxconnections=6, # 連接配接池允許的最大連接配接數,0和None表示不限制連接配接數

mincached=2, # 初始化時,連結池中至少建立的空閑的連結,0表示不建立

maxcached=5, # 連結池中最多閑置的連結,0和None不限制

maxshared=3, # 連結池中最多共享的連結數量,0和None表示全部共享。PS: 無用,因為pymysql和MySQLdb等子產品的 threadsafety都為1,所有值無論設定為多少,_maxcached永遠為0,是以永遠是所有連結都共享。

blocking=True, # 連接配接池中如果沒有可用連接配接後,是否阻塞等待。True,等待;False,不等待然後報錯

maxusage=None, # 一個連結最多被重複使用的次數,None表示無限制

setsession=[], # 開始會話前執行的指令清單。

ping=0,

# ping MySQL服務端,檢查是否服務可用。

host='127.0.0.1',

port=3306,

user='root',

password='123456',

database='test',

charset='utf8'

)

def func():

# 檢測目前正在運作連接配接數的是否小于最大連結數,如果不小于則:等待或報raise TooManyConnections異常

# 否則

# 則優先去初始化時建立的連結中擷取連結 SteadyDBConnection。

# 然後将SteadyDBConnection對象封裝到PooledDedicatedDBConnection中并傳回。

# 如果最開始建立的連結沒有連結,則去建立一個SteadyDBConnection對象,再封裝到PooledDedicatedDBConnection中并傳回。

# 一旦關閉連結後,連接配接就傳回到連接配接池讓後續線程繼續使用。

conn = POOL.connection()

# print(th, '連結被拿走了', conn1._con)

# print(th, '池子裡目前有', pool._idle_cache, '\r\n')

cursor = conn.cursor()

cursor.execute('select * from user')

result = cursor.fetchall()

print(result)

conn.close()

if __name__ == '__main__':

func()