37,720
社区成员
发帖
与我相关
我的任务
分享
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()