实际上,我正在尝试通过pymysql用多个进程更新一个表,每个进程读取一个从一个巨大的CSV文件中分离出来的CSV文件以提高速度。但是当我运行脚本时,我得到了Lock wait timeout exceeded; try restarting transaction exception。在搜索这个网站上的帖子后,我发现有一篇帖子提到了设置或构建built-in LOAD_DATA_INFILE,但没有关于它的细节。我怎样才能用'pymysql‘来达到我的目标?
下面是作业方法:
`def importprogram(path, name):
begin = time.time()
print('begin to import program' + name + ' info.')
# "c:\\sometest.csv"
file = open(path, mode='rb')
csvfile = csv.reader(codecs.iterdecode(file, 'utf-8'))
connection = None
try:
connection = pymysql.connect(host='a host', user='someuser', password='somepsd', db='mydb',
cursorclass=pymysql.cursors.DictCursor)
count = 1
with connection.cursor() as cursor:
sql = '''update sometable set Acolumn='{guid}' where someid='{pid}';'''
next(csvfile, None)
for line in csvfile:
try:
count = count + 1
if ''.join(line).strip():
command = sql.format(guid=line[2], pid=line[1])
cursor.execute(command)
if count % 1000 == 0:
print('program' + name + ' cursor execute', count)
except csv.Error:
print('program csv.Error:', count)
continue
except IndexError:
print('program IndexError:', count)
continue
except StopIteration:
break
except Exception as e:
print('program' + name, str(e))
finally:
connection.commit()
connection.close()
file.close()
print('program' + name + ' info done.time cost:', time.time()-begin)`和多处理方法:
import multiprocessing as mp
def multiproccess():
pool = mp.Pool(3)
results = []
paths = ['C:\\testfile01.csv', 'C:\\testfile02.csv', 'C:\\testfile03.csv']
name = 1
for path in paths:
results.append(pool.apply_async(importprogram, args=(path, str(name))))
name = name + 1
print(result.get() for result in results)
pool.close()
pool.join()主要的方法是:
if __name__ == '__main__':
multiproccess()我是Python的新手。我怎么才能让代码或方式本身出错呢?是否应该只使用一个进程来完成数据读取和导入?
发布于 2018-12-28 21:16:18
您的问题是您超过了从服务器获取响应所允许的时间,因此客户端会自动超时。根据我的经验,将等待超时调整为6000秒左右,合并成一个CSV,然后让数据导入即可。此外,我建议直接从MySQL而不是Python运行查询。
我通常将CSV数据从Python导入MySQL的方法是通过INSERT ...价值观...方法,我只在需要对数据进行某种操作(即将不同的行插入到不同的表中)时才这样做。
我喜欢你的方法,并理解你的想法,但在现实中没有必要。插入的好处是...价值观...方法是您不会遇到任何超时问题。
https://stackoverflow.com/questions/53953484
复制相似问题