python使用多线程查询数据库的实现示例

时间:2021-05-22

一.背景:

当数据量过大时,一个程序的执行时间就会主要花费在等待单次查询返回结果,在这个过程中cpu无疑是处于等待io的空闲状态的,这样既浪费了cpu资源,又花费了大量时间(当然这里主要说多线程,批量查询不在考虑范围,总会存在不能批量查询的情况),在这种非密集型运算(及大量占用cpu资源)的情况下在python中无疑运用多线程是一个非常棒的选择。

二.知识点:

数据库连接池的运用及优势,python中多线程的运用,队列的运用

数据库连接池:限制了数据库的连接最大个数,每次连接都是可以重复使用的,当然也可以限制每个连接的重复使用次数(这个在这里是没必要的),需要注意的是设置的数据库的最大连接个数最好要大于我们自己开的最大线程个数,一般逻辑是每个线程占用一个数据库连接可以使程序达到最大速度,如果小于则可能存在同时连接个数大于数据库允许的最大连接个数的风险。使用数据库连接池的优势在于,python多线程并发操作数据库,会存在链接数据库超时、数据库连接丢失、数据库操作超时等问题,而数据库连接池提供线程间可共享的数据库连接,并自动管理连接。

python多线程:在程序等待io的时间里调用多线程去数据库执行查询操作。

队列:这个就是数据结构里面的知识了,一般队列的常用模式先进先出队列。(这里主要用的是队列取一个数就少一个数的原理,其实用列表也可以实现,他的先进先出主要强调的是一个顺序关系,这一点到没用上,就当是练练手了)

三.两段代码作比较:

数据库的截图:

第一段代码:正常循环查询并打印出执行时间

#!/usr/bin/python# -*- coding=utf-8 -*-import timeimport threadingimport MySQLdbimport Queuefrom MySQLdb.cursors import DictCursorfrom DBUtils.PooledDB import PooledDBdef mysql_connection(): host = 'localhost' user = 'root' port = 3306 password = '123456' db = 'test' 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 poolstart = time.time()pool = mysql_connection()for id in range(50): con = pool.connection() cur = con.cursor() sql = '''select id,name,age,weight from test where id = %s '''%id cur.execute(sql) time.sleep(0.5) result = cur.fetchall() if result: print('this is tread %s (%s,%s,%s,%s)'%(id,result[0]['id'],result[0]['name'],result[0]['age'],result[0]['weight'])) else: print('this tread %s result is none'%id)end = time.time() - startprint(end)

执行结果:

第二段代码:限制数据库连接池最大15个连接,用队列限制最大线程个数为10个

#!/usr/bin/python# -*- coding=utf-8 -*-import timeimport threadingimport MySQLdbimport Queuefrom MySQLdb.cursors import DictCursorfrom DBUtils.PooledDB import PooledDBdef mysql_connection(): host = 'localhost' user = 'root' port = 3306 password = '123456' db = 'test' 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 pooldef tread_connection_db(id): con = pool.connection() cur = con.cursor() sql = '''select id,name,age,weight from test where id = %s '''%id cur.execute(sql) time.sleep(0.5) result = cur.fetchall() if result: print('this is tread %s (%s,%s,%s,%s)'%(id,result[0]['id'],result[0]['name'],result[0]['age'],result[0]['weight'])) else: print('this tread %s result is none'%id) con.close()if __name__=='__main__': start = time.time() #创建线程连接池,最大限制15个连接 pool = mysql_connection() #创建队列,队列的最大个数及限制线程个数 q=Queue.Queue(maxsize=10) #测试数据,多线程查询数据库 for id in range(50): #创建线程并放入队列中 t = threading.Thread(target=tread_connection_db, args=(id,)) q.put(t) #队列队满 if q.qsize()==10: #用于记录线程,便于终止线程 join_thread = [] #从对列取出线程并开始线程,直到队列为空 while q.empty()!=True: t = q.get() join_thread.append(t) t.start() #终止上一次队满时里面的所有线程 for t in join_thread: t.join() end = time.time() - start print(end)

程序备注应该还算比较清晰的哈,程序执行结果:

四.结论:

看结果说话

到此这篇关于python使用多线程查询数据库的实现示例的文章就介绍到这了,更多相关python 多线程查询数据库内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章