python多线程操作mysql连接池报AttributeError: 'NoneType' object has no attribute 'read'

近来在看python,然后准备使用python的多线程操作mysql的连接池(使用mysql的连接池效率会更高),先上代码,代码也比较简单,稍微会一点python的人都能看的懂的:

import threading
from DBUtils.PooledDB import PooledDB
import time
import pymysql
lock = threading.Lock()

class MysqlHelper():
   def __init__(self):
      self.__pool = PooledDB(creator=pymysql,
                  mincached=1,
                  maxcached=3,
                  maxconnections=3,
                  blocking=True,
                  user="root",
                  passwd="123456",
                  db="wangchao")

   def getConn(self):
      self.conn = self.__pool.connection()
      self.cursor = self.conn.cursor()

   def dispose(self):
      self.cursor.close()
      self.conn.close()

   def getOne(self, sql):
      self.getConn()
      self.cursor.execute(sql)
      rows = self.cursor.fetchall()
      print(rows)
      self.dispose()

def test1(pool):
   strsql = "select * from csv_test"
   while True:
      #lock.acquire()
      pool.getConn()

      pool.getOne(strsql)
      #lock.release()
      time.sleep(1)


def main(pool):
   for i in range(5):
      threading.Thread(target=test1, args=(pool,)).start()

if __name__ == "__main__":
   mysqlhelper = MysqlHelper()
   main(mysqlhelper)
   while True:
      time.sleep(1)

当时当代码跑起来的时候(我用的是pycharm开发的),一直出错,出现的错误有:

AttributeError: 'NoneType' object has no attribute 'read'

struct.error: unpack_from requires a buffer of at least 8 bytes,已报错线程就直接退出了(当然线程处理函数写的很简单),在网上查了很多资料都是单线程操作mysql连接池的,很少有多线程的例子,直接把错误贴到网上也找不到解决办法。但是看了这博友https://blog.csdn.net/qq_29666899/article/details/82990599的帖子,我试了一下在线程处理函数中,使用连接池先后都加锁(即把红色生效),然后就不会报错了,现在什么原因也不是很清楚,还请路过的大神指点。但是我感觉应该是多线程共享mysql连接池的问题。

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值