温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中怎么利用多线程操作数据库

发布时间:2021-06-17 14:50:32 来源:亿速云 阅读:687 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关Python中怎么利用多线程操作数据库,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

python多线程并发操作数据库,会存在链接数据库超时、数据库连接丢失、数据库操作超时等问题。

解决方法:使用数据库连接池,并且每次操作都从数据库连接池获取数据库操作句柄,操作完关闭连接返回数据库连接池。

*连接数据库需要设置charset = 'utf8', use_unicode = True,不然会报中文乱码问题

*网上说解决python多线程并发操作数据库问题,连接时使用self.conn.ping(True)(检查并保持长连接),但是我这边亲测无法解决,建议还是使用数据库连接池

python多线程代码:

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数据库连接池代码:

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中怎么利用多线程操作数据库就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI