【新手提问】关于在ThreadPoolExecutor线程池中插入mysql错误

qq_31201951 2018-05-10 10:07:02
py新手正在学习线程池,发现在线程中插入mysql报错,但是如果不用线程池单纯循环没有报错,打印mysql语句也没有问题,不知道是什么问题,请各位大神帮解答。先上代码

from concurrent.futures import ThreadPoolExecutor
import pymysql
class shiyan(object):
def __init__(self):
self.mysqldir = "127.0.0.1"
self.mysqluser = "root"
self.mysqlpassword = "root"
self.dbase = "test"
def test(self):
testlist = ['a','b','c']
db = self.init_mysql()
with ThreadPoolExecutor(3) as executor:
for test in testlist:
data = {}
data['test'] = test
data['db'] = db
executor.submit(self.add_mysql,data)
def init_mysql(self):
try:
db = pymysql.connect(self.mysqldir,self.mysqluser,self.mysqlpassword,self.dbase, use_unicode=True, charset="utf8" )
print("数据库连接成功")
except Exception as e:
print("数据库无法正确链接")
return
cursor = db.cursor()

cursor.execute('SET NAMES utf8;')

cursor.execute('SET CHARACTER SET utf8;')

cursor.execute('SET character_set_connection=utf8;')
return db
def add_mysql(self,data):
sql = 'insert into test (test) values("%s")' % (data['test'])
print(sql)
cursor = data['db'].cursor()
try:
# 执行sql语句
cursor.execute(sql)
print("插入数据成功")
# 提交到数据库执行
data['db'].commit()
except Exception as e:
# 如果发生错误则回滚
print(e)
data['db'].rollback()

sy = shiyan()
sy.test()

报错提示
...全文
750 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_31201951 2018-05-11
  • 打赏
  • 举报
回复
我测试了一下,如果在add_mysql执行init_mysql创建mysql链接,比直接使用循环还慢几倍,完全不合理啊
qq_31201951 2018-05-11
  • 打赏
  • 举报
回复
有没有人回答,如果按照1楼的说法,每次执行线程函数都创建一个链接,不仅挤占我数据库的资源而且也增加程序运行的时间。难道用线程池都是这样操作的吗?按照我个人的理解python的线程同时段只有一个线程在运行,那我只创建一个mysql链接应该是没问题的啊。请各位大神指点。
qq_31201951 2018-05-10
  • 打赏
  • 举报
回复
如果这样我的testlist长度是1000个的话,不久会有1000个连接了,这样不会太占资源吗?
oyljerry 2018-05-10
  • 打赏
  • 举报
回复
db不要多线程共享,每个线程自己connect

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧