近来在看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连接池的问题。