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

作者:下划线隐患者 时间:2024-01-21 18:34:59 

一.背景:

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

二.知识点:

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

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

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

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

三.两段代码作比较:

数据库的截图:

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

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


#!/usr/bin/python
# -*- coding=utf-8 -*-
import time
import threading
import MySQLdb
import Queue
from MySQLdb.cursors import DictCursor
from DBUtils.PooledDB import PooledDB

def 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 pool

start = 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() - start
print(end)

执行结果:

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

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


#!/usr/bin/python
# -*- coding=utf-8 -*-
import time
import threading
import MySQLdb
import Queue
from MySQLdb.cursors import DictCursor
from DBUtils.PooledDB import PooledDB

def 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 pool

def 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使用多线程查询数据库的实现示例

四.结论:

看结果说话

来源:https://blog.csdn.net/zer_o_o/article/details/86742430

标签:python,多线程,查询,数据库
0
投稿

猜你喜欢

  • python 创建一个空dataframe 然后添加行数据的实例

    2022-05-08 01:51:59
  • vue3配置全局参数(挂载全局方法)以及组件的使用

    2023-07-02 16:45:46
  • django之跨表查询及添加记录的示例代码

    2022-11-23 14:44:25
  • C#从数据库读取图片并保存的两种方法

    2024-01-12 14:39:22
  • keras实现VGG16 CIFAR10数据集方式

    2023-08-19 08:27:08
  • iscroll动态加载数据完美解决方法

    2024-04-10 13:59:01
  • Httprunner简介、安装及基本使用教程

    2022-07-13 01:52:52
  • Spring数据库事务的实现机制讲解

    2024-01-19 11:32:10
  • python制作一个桌面便签软件

    2021-02-23 05:20:40
  • 将一个图片以二进制值的形式存入Xml文件中

    2008-09-04 11:24:00
  • Nodejs中调用系统命令、Shell脚本和Python脚本的方法和实例

    2024-05-13 09:29:17
  • Python算法应用实战之队列详解

    2022-08-21 11:49:33
  • 如何把数组转换成字符串?

    2009-11-06 13:49:00
  • 微信跳一跳游戏python脚本

    2022-03-31 02:24:27
  • 十个Golang开发中应该避免的错误总结

    2024-04-25 15:05:14
  • SQL Server的触发器你了解多少

    2024-01-14 21:15:57
  • python 数据挖掘算法的过程详解

    2022-11-17 09:09:19
  • JavaScript中var let const的用法有哪些区别

    2024-05-09 15:06:33
  • 在ASP.NET页面中如何利用JAVASCRIPT脚本向IFRAMES和POPUP传值

    2007-09-23 13:18:00
  • 解决idea git切换多个分支后maven不生效的问题

    2023-06-28 17:48:13
  • asp之家 网络编程 m.aspxhome.com