看代碼,
from flask import Flask from db import POOL import pymysql app = Flask(__name__) app.secret_key ='sdfsdfsdf' @app.route('/index') def index(): # 第一步:缺點:每次請求反復創建數據庫連接,連接數太多。 # conn = pymysql.connect() # cursor = conn.cursor() # cursor.execute('select * from tb where id > %s',[5,]) # result = cursor.fetchall() # cursor.close() # conn.close() # print(result)
對於這種方式,每來一個用戶請求,都要去創建一個鏈接。對於數據庫來說,過分了。可並發,但是連接數太多。
就算你改成在全局創建,只用一個鏈接,但是會變成串行。
如果是多線程的話,這樣的方式是不是會報錯哦?pymysql它同一時間只能處理一個線程。
那來,我們這樣玩,還是在將鏈接操作放在全局。
# 第二步:缺點,不能支持並發 # pymysql.threadsafety # with LOCK: # cursor = CONN.cursor() # cursor.execute('select * from tb where id > %s', [5, ]) # result = cursor.fetchall() # cursor.close() # # print(result)
加把鎖。這樣支持多線程了吧?
可是。。。 它支持並發嗎? 並不支持
讓它倆折中一下,這樣來玩。
基於DBUtils實現數據鏈接池。
模式一:每個線程獨立創建自己的鏈接,無論該線程使用多少次,用的都是同一個。該線程關閉時,偽關閉,本地線程再次調用時,繼續使用最開始創建的鏈接。
何時關閉? 線程不終止,永不關閉!所有線程終止數據庫連接,該線程關閉。
模式二:多線程間不分彼此。 創建一個連接池(此處才體現出池),為所有線程提供鏈接。
使用時從池里獲取,使用完畢后,放回連接池。
拿的時候,pop出來,用完再append進去。
連接池里的連接,排隊依次被使用。
補充:共享時,可設置最多共享數???
文檔里寫的可以設置最大共享數,比如我池里有10個線程,最大共享數設置5,你是否認為最多5個可以被來回玩?
NO!源碼里面,清清楚楚的寫到:大家都是朋友,不見外,一起玩。
pymsql里面的threadsafety=1,代表:無論你如何使用,所有連接都可被重復使用。
本地線程示例:保證每個線程都有數據庫連接,都持有自己的一份數據,在操作時,不會相互影響。

import threading import time # 本地線程對象 local_values = threading.local() def func(num): """ # 第一個線程進來,本地線程對象會為他創建一個 # 第二個線程進來,本地線程對象會為他創建一個 :param num: :return: """ local_values.name = num # 4 # 線程停下來了 time.sleep(2) print(local_values.name, threading.current_thread().name) for i in range(5): th = threading.Thread(target=func, args=(i,), name='線程%s' % i) th.start()
模式二示例:

import time import pymysql import threading 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='127.0.0.1', port=3306, user='root', password='123', database='pooldb', charset='utf8' ) def func(): # 檢測當前正在運行連接數的是否小於最大鏈接數,如果不小於則:等待或報raise TooManyConnections異常 # 否則 # 則優先去初始化時創建的鏈接中獲取鏈接 SteadyDBConnection。 # 然后將SteadyDBConnection對象封裝到PooledDedicatedDBConnection中並返回。 # 如果最開始創建的鏈接沒有鏈接,則去創建一個SteadyDBConnection對象,再封裝到PooledDedicatedDBConnection中並返回。 # 一旦關閉鏈接后,連接就返回到連接池讓后續線程繼續使用。 # PooledDedicatedDBConnection conn = POOL.connection() # print(th, '鏈接被拿走了', conn1._con) # print(th, '池子里目前有', pool._idle_cache, '\r\n') cursor = conn.cursor() cursor.execute('select * from tb1') result = cursor.fetchall() conn.close() conn = POOL.connection() # print(th, '鏈接被拿走了', conn1._con) # print(th, '池子里目前有', pool._idle_cache, '\r\n') cursor = conn.cursor() cursor.execute('select * from tb1') result = cursor.fetchall() conn.close() func()
模式二連接池用法:
import time import pymysql import threading 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='127.0.0.1', port=3306, user='root', password='123', database='pooldb', charset='utf8' )
from flask import Flask from db import POOL import pymysql app = Flask(__name__) app.secret_key ='sdfsdfsdf' @app.route('/index') def index(): conn = POOL.connection() cursor = conn.cursor() cursor.execute('select * from tb1') result = cursor.fetchall() conn.close() return '執行成功' if __name__ == '__main__': # app.__call__ app.run()