首页 > 解决方案 > MysqlDB - 查询被杀死

问题描述

我有一个 python 脚本,它试图转储一个包含 750 万行的表,但在大约 20 秒后查询被杀死。我使用 MysqlDB 连接远程数据库。我读到 MySQL --quick 选项可能会有所帮助,因为它不会缓存每个查询结果。如何在我的 python 脚本中使用这个选项?

编辑:我使用 pdb。似乎执行查询是因为所有 750 万行都存在于变量“行”中。这是我的脚本:

def dumpDatasetToCsv(self, name):
    cur = self._con.cursor()
    res = cur.execute(self._query)
    rows = cur.fetchall()
    column_names = [i[0] for i in cur.description]
    dumpFilePath=cfg.EtlConfiguration.exportDirectory +  self._dataSetName+ '-' + self.csvFileSuffix + '.csv'
    fp = open(dumpFilePath ,'w')
    myFile = csv.writer(fp, lineterminator = '\n') 
    list_to_export=[]
    for row in rows: list_to_export.append(list(row))
    for row in list_to_export: row.insert(1, self.csvFileSuffix)
    myFile.writerows(list_to_export)
    fp.close()

代码在“for row in rows: list_to_export.append(list(row))”行崩溃

此外,当我使用 pdb 并在上述行之前停止执行脚本时,我只是逐行粘贴代码的其余行,一切正常。输出文件已创建。

标签: pythonmysqlmysql-python

解决方案


750 万行可能会导致您的内存填满并导致进程被终止。你想做这样的事情:

with open('outfile.csv', 'w') as f:
   while True:
      rows = cursor.fetchmany(1000)
      if not rows:
          break
      f.write(...)

推荐阅读