1. 程式人生 > >資料庫連線池DBUtils使用

資料庫連線池DBUtils使用

一、簡介

  DBUtils簡單說python實現的執行緒化資料庫連線(連線池),DBUtils支援所有遵循 DP-API 2規範的資料庫連線模組,例如:mysql、sqlserver、oracle、sqlite3等,更多請參考官網: https://cito.github.io/DBUtils/UsersGuide.html。   

二、安裝使用

安裝

pip3 install DBUtils

使用

在使用上通常使用其PooledDB和PersistentDB,以下將介紹這兩種方式的使用方法:
  • PersistentDB:為每個執行緒建立一個連線,執行緒即使呼叫了close方法,也不會關閉,只是把連線重新放到連線池,供自己執行緒再次使用。當執行緒終止時,連線自動關閉。
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author:wd
from DBUtils.PersistentDB import PersistentDB
import pymysql

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(建立cursor時候), 4 = when a query is executed, 7 = always closeable=False, # 如果為False時, conn.close() 實際上被忽略,供下次使用,再執行緒關閉時,才會自動關閉連結。如果為True時, conn.close()則關閉連結,那麼再次呼叫pool.connection時就會報錯,因為已經真的關閉了連線(pool.steady_connection()可以獲取一個新的連結)
threadlocal=None, # 本執行緒獨享值得物件,用於儲存連結物件,如果連結物件被重置 host='10.1.210.33', port=3306, user='root', password='1234qwer', database='devops', charset='utf8' ) def query(): conn = POOL.connection(shareable=False) cursor = conn.cursor() cursor.execute('select * from account') result = cursor.fetchall() print(result) cursor.close() conn.close() if __name__=='__main__': query()

  • PooledDB:建立一批連線到連線池,供所有執行緒共享使用,由於pymysql、MySQLdb等threadsafety值為1,所以該模式連線池中的執行緒會被所有執行緒共享。
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author:wd

import pymysql
from DBUtils.PooledDB import PooledDB, SharedDBConnection
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='10.1.210.33',
    port=3306,
    user='root',
    password='1234qwer',
    database='devops',
    charset='utf8'
)


def query():
    # 檢測當前正在執行連線數的是否小於最大連結數,如果不小於則:等待或報raise TooManyConnections異常
    # 否則
    # 則優先去初始化時建立的連結中獲取連結 SteadyDBConnection。
    # 然後將SteadyDBConnection物件封裝到PooledDedicatedDBConnection中並返回。
    # 如果最開始建立的連結沒有連結,則去建立一個SteadyDBConnection物件,再封裝到PooledDedicatedDBConnection中並返回。
    # 一旦關閉連結後,連線就返回到連線池讓後續執行緒繼續使用。
    conn = POOL.connection()
    cursor = conn.cursor()
    cursor.execute('select * from account')
    result = cursor.fetchall()
    print(result)
    conn.close()   #不是真正關閉,而是重新放回了連線池

if __name__=='__main__':
    query()