pip install dbutils==1.3pip install mysqlclient==2.0.1
import time
import threading
import mysqldb
import queue
from mysqldb.cursors import dictcursor
from dbutils.pooleddb import pooleddb
def mysql_connection():
host = 'host'
user = 'user'
port = 3306
password = 'pwd'
db = 'mysql'
charset = 'utf8'
limit_count = 3 # 最低預啟動資料庫連線數量
pool = pooleddb(mysqldb, limit_count, maxconnections=15, host=host, user=user, port=port, passwd=password, db=db,
charset=charset,
use_unicode=true, cursorclass=dictcursor)
return pool
def tread_connection_db():
con = pool.connection()
cur = con.cursor()
sql = """
select * from ....
"""cur.execute(sql)
result = cur.fetchall()
con.close()
return result
class mythread(threading.thread):
def __init__(self, func, args):
super(mythread, self).__init__()
self.func = func
self.args = args
def run(self):
self.result = self.func(*self.args)
def get_result(self):
try:
return self.result
except exception:
return none
if __name__ == '__main__':
start = time.time()
# 建立執行緒連線池
pool = mysql_connection()
# 建立佇列,佇列的最大個數及限制執行緒個數
q = queue.queue(maxsize=12)
# 測試資料,多執行緒查詢資料庫
for i in range(12):
# 建立執行緒並放入佇列中
# t = mythread(target=tread_connection_db, args=(id,))
t = mythread(tread_connection_db, args=(i,))
q.put(t)
# 佇列隊滿
if q.qsize() == 12:
# 用於記錄執行緒,便於終止執行緒
join_thread =
# 從對列取出執行緒並開始執行緒,直到隊列為空
while q.empty() != true:
t = q.get()
t.start()
# 終止上一次隊滿時裡面的所有執行緒
for t in join_thread:
t.join()
for t in join_thread:
print(t.get_result())
end = time.time() - start
print(end)
python使用多執行緒查詢資料庫
當資料量過大時,乙個程式的執行時間就會主要花費在等待單次查詢返回結果,在這個過程中cpu無疑是處於等待io的空閒狀態的,這樣既浪費了cpu資源,又花費了大量時間 當然這裡主要說多執行緒,批量查詢不在考慮範圍,總會存在不能批量查詢的情況 在這種非密集型運算 及大量占用cpu資源 的情況下在python...
在多執行緒裡查詢資料庫並填充dataGrid
public delegate void mydelegate datatable dt private void b ianjia click object sender,system.eventargs e catch system.exception ex void threadwork el...
Python3多執行緒寫資料庫
import pymysql import threading classdb def init self,host none username none pwd none dbname none self.pool self.host host self.username username sel...