Python基于多线程操作数据库相关问题分析

yipeiwu_com6年前Python基础

本文实例分析了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相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》、《Python+MySQL数据库程序设计入门教程》及《Python常见数据库操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python机器学习库xgboost的使用

python机器学习库xgboost的使用

1.数据读取 利用原生xgboost库读取libsvm数据 import xgboost as xgb data = xgb.DMatrix(libsvm文件) 使用sk...

python2 中 unicode 和 str 之间的转换及与python3 str 的区别

在python2中字符串分为 unicode 和 str 类型   Str To Unicode 使用decode(), 解码   Unicode To Str 使用encode()...

django基础之数据库操作方法(详解)

django基础之数据库操作方法(详解)

Django 自称是“最适合开发有限期的完美WEB框架”。本文参考《Django web开发指南》,快速搭建一个blog 出来,在中间涉及诸多知识点,这里不会详细说明,如果你是第一次接触...

在arcgis使用python脚本进行字段计算时是如何解决中文问题的

在arcgis使用python脚本进行字段计算时是如何解决中文问题的

一、引言   在arcgis打开一个图层的属性表,可以对属性表的某个字段进行计算,但是在平常一般都是使用arcgis提供的字段计算器的界面进行傻瓜式的简答的赋值操作,并没有使用到脚本对字...

Python数据结构与算法之二叉树结构定义与遍历方法详解

本文实例讲述了Python数据结构与算法之二叉树结构定义与遍历方法。分享给大家供大家参考,具体如下: 先序遍历,中序遍历,后序遍历 ,区别在于三条核心语句的位置 层序遍历  采...