本文實例分析了Python多線程操作數據庫相關問題。分享給大家供大家參考,具體如下:
python多線程并發操作數據庫,會存在鏈接數據庫超時、數據庫連接丟失、數據庫操作超時等問題。
解決方法:使用數據庫連接池,并且每次操作都從數據庫連接池獲取數據庫操作句柄,操作完關閉連接返回數據庫連接池。
*連接數據庫需要設置
charset = 'utf8', use_unicode = True
,不然會報中文亂碼問題*網上說解決python多線程并發操作數據庫問題,連接時使用
self.conn.ping(True)
(檢查并保持長連接),但是我這邊親測無法解決,建議還是使用數據庫連接池
python多線程代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
import threading class MyThread(threading.Thread): def __init__( self , name, count, exec_object): threading.Thread.__init__( self ) self .name = name self .count = count self .exec_object = exec_object def run( self ): while self .count > = 0 : count = count - 1 self .exec_object.execFunc(count) thread1 = MyThread( 'MyThread1' , 3 , ExecObject()) thread2 = MyThread( 'MyThread2' , 5 , ExecObject()) thread1.start() thread2.start() thread1.join() # join方法 執行完thread1的方法才繼續主線程 thread2.join() # join方法 執行完thread2的方法才繼續主線程 # 執行順序 并發執行thread1 thread2,thread1和thread2執行完成才繼續執行主線程 # ExecObject類是自定義數據庫操作的業務邏輯類 # ########join方法詳解######## thread1 = MyThread( 'MyThread1' , 3 , ExecObject()) thread2 = MyThread( 'MyThread2' , 5 , ExecObject()) thread1.start() thread1.join() # join方法 執行完thread1的方法才繼續主線程 thread2.start() thread2.join() # join方法 執行完thread2的方法才繼續主線程 # 執行順序 先執行thread1,執行完thread1再執行thread2,執行完thread2才繼續執行主線程 |
mysql數據庫連接池代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
import MySQLdb from DBUtils.PooledDB import PooledDB class MySQL: host = 'localhost' user = 'root' port = 3306 pasword = '' db = 'testDB' charset = 'utf8' pool = None limit_count = 3 # 最低預啟動數據庫連接數量 def __init__( self ): self .pool = PooledDB(MySQLdb, self .limit_count, host = self .host, user = self .user, passwd = self .pasword, db = self .db, port = self .port, charset = self .charset, use_unicode = True ) def select( self , sql): conn = self .pool.connection() cursor = conn.cursor() cursor.execute(sql) result = cursor.fetchall() cursor.close() conn.close() return result def insert( self , table, sql): conn = self .pool.connection() cursor = conn.cursor() try : cursor.execute(sql) conn.commit() return { 'result' : True , 'id' : int (cursor.lastrowid)} except Exception as err: conn.rollback() return { 'result' : False , 'err' :err} finally : cursor.close() conn.close() |
希望本文所述對大家Python程序設計有所幫助。
原文鏈接:https://blog.csdn.net/mxdzchallpp/article/details/80411514