Python數據庫連接池DBUtils(基於pymysql模塊連接數據庫)


安裝

pip3 install DBUtils

DBUtils是Python的一個用於實現數據庫連接池的模塊。

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

# BDUtils數據庫鏈接池:
模式一:基於threaing.local實現為每一個線程創建一個連接,關閉是偽關閉,當前線程可以重復
模式二:連接池原理
    如果有三個線程來數據庫中獲取連接:
        如果三個同時來的,一人給一個連接;
        如果一個一個來,有時間間隔,用一個連接就可以為三個線程提供服務;
        其他情況:
            有可能:1個連接就可以為三個線程提供服務
            有可能:2個連接就可以為三個線程提供服務
            有可能:3個連接就可以為三個線程提供服務
    PS:maxshared在使用pymysql中均無用。鏈接數據庫的模塊:只有threadsafety>1的時候才有用。

模式一:為每個線程創建一個連接,線程即使調用了close方法,也不會關閉,只是把連接重新放到連接池,供自己線程再次使用。當線程終止時,連接自動關閉。(如果線程比較多還是會創建很多連接,推薦使用模式二)

import pymysql
from DBUtils.PersistentDB import PersistentDB

POOL = PersistentDB(
    creator=pymysql,  # 使用鏈接數據庫的模塊
    maxusage=None,    # 一個鏈接最多被重復使用的次數,None表示無限制
    setsession=[],    # 開始會話前執行的命令列表。如:["set datestyle to ...", "set time zone ..."]
    ping=0,
    # 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
    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="",
    database="code_record",
    charset="utf8"
)

def func():
    conn = POOL.connection(shareable=False)
    cursor = conn.cursor()
    cursor.execute("select * from userinfo")
    ret = cursor.fetchall()
    print(ret)
    cursor.close()
    conn.close()

func()
View Code

模式二:創建一批連接到連接池,供所有線程共享使用,使用完畢后再放回到連接池。(由於pymysql、MySQLdb等threadsafety值為1,所以該模式連接池中的線程會被所有線程共享。)

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=[],  # 開始會話前執行的命令列表。如:["set datestyle to ...", "set time zone ..."]
    ping=0,
    # 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
    host="127.0.0.1",
    port=3306,
    user="root",
    password="",
    database="code_record",
)

def func():
    # 檢測當前正在運行連接數的是否小於最大鏈接數,如果不小於則:等待或報raise TooManyConnections異常
    # 否則
    # 則優先去初始化時創建的鏈接中獲取鏈接 SteadyDBConnection。
    # 然后將SteadyDBConnection對象封裝到PooledDedicatedDBConnection中並返回。
    # 如果最開始創建的鏈接沒有鏈接,則去創建一個SteadyDBConnection對象,再封裝到PooledDedicatedDBConnection中並返回。
    # 一旦關閉鏈接后,連接就返回到連接池讓后續線程繼續使用。
    conn = POOL.connection()
    cursor = conn.cursor()
    cursor.execute('select * from userinfo')
    result = cursor.fetchall()
    print(result)
    conn.close()

func()
View Code

為什么要使用數據庫連接池呢?

如果沒有連接池,使用pymysql來連接數據庫時,單線程應用完全沒有問題;但如果涉及到多線程應用那么就需要加鎖,一旦加鎖那么連接勢必就會排隊等待(無法並發),當請求比較多時,性能就會降低了。

import pymysql
import threading
from threading import RLock

LOCK = RLock()
CONN = pymysql.connect(host='127.0.0.1',
                       port=3306,
                       user='root',
                       password='',
                       database='code_record',
                       charset='utf8')

def task(arg):
    with LOCK:
        cursor = CONN.cursor()
        cursor.execute('select * from userinfo')
        ret = cursor.fetchall()
        cursor.close()
        print(ret)

for i in range(10):
    t = threading.Thread(target=task, args=(i,))
    t.start()
加鎖
import pymysql
import threading
CONN = pymysql.connect(host='127.0.0.1',
                       port=3306,
                       user='root',
                       password='',
                       database='code_record',
                       charset='utf8')

def task(arg):
    cursor = CONN.cursor()
    cursor.execute('select * from userinfo')
    ret = cursor.fetchall()
    cursor.close()
    print(ret)

for i in range(10):
    t = threading.Thread(target=task, args=(i,))
    t.start()
無鎖(報錯)

 


免責聲明!

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



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