我正在解析一个文本文件,然后使用基于该表中主键从文件中解析出的值来更新mysql表列。我最初使用sqlite进行此操作,然后写入本地的sqlite文件,但没有遇到任何问题。现在,我正在写一个新的mysql数据库,当使用executemany更新具有从文本文件中解析出来的大列表的表时,更新会花费很长时间,有时需要20-30秒,在某些情况下,列表中有〜50k个条目永远不会成功写任何东西。
我尝试使用executemany,因为这似乎可以减轻使用sqlite时的性能问题,一旦executemany调用中使用了足够大的列表,代码将停止工作。从我读过的书中,我应该将executemany与INSERT和ON DUPLICATE KEY UPDATE一起使用,但这会产生截断的数据错误。
def strip_file(x):
filePath = 'somefile.txt'
with open(filePath) as file:
for i, line in enumerate(file):
if i > x:
indicatorName = re.findall(re.escape('some text')+"(.*?)"+re.escape("blah"),line)
if indicatorName:
indicatorCount = re.findall(re.escape('number')+"(.*?)"+re.escape("|"),line)
indicatorTime = re.findall(re.escape('time')+"(.*?)"+re.escape('end'),line)
for i in indicatorTime:
i.strip()
indicatorName = re.findall(re.escape('ending' + indicatorCount[0] +'|')+"(.*?)"+re.escape('|'),line)
indicatorNameInd = indicatorName[0].split(",")
indicatorNameInd = filter(None, indicatorNameInd)
for i in indicatorNameInd:
i.strip()
indicatorTimeSeq = [indicatorTime]*len(indicatorNameInd)
indicatorTimeList = list(chain(*indicatorTimeSeq))
indicatorSeq = zip(indicatorTimeList, indicatorNameInd)
cursor.execute('SET autocommit=0')
sql = 'UPDATE IndicatorData SET IndicatorTime=%s WHERE IndicatorID=%s'
cursor.executemany(sql, indicatorSeq)
conn.commit()
如果指标seq较大,此方法将停止写入。
在重复的密钥更新上使用INSERT:
sql = 'INSERT INTO IndicatorData (IndID, IndTime) VALUES (%s,%s) ON DUPLICATE KEY UPDATE VALUES IndTime = %s'
cursor.executemany(sql, indicatorSeq)
我希望如果IndID列中存在列表中关联的IndicatorID,则表中的IndTime将更新。相反,我收到此错误:
ProgrammingError:处理格式参数失败; Python'tuple'无法转换为MySQL类型