python - 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 并在上述行之前停止执行脚本时,我只是逐行粘贴代码的其余行,一切正常。输出文件已创建。
解决方案
750 万行可能会导致您的内存填满并导致进程被终止。你想做这样的事情:
with open('outfile.csv', 'w') as f:
while True:
rows = cursor.fetchmany(1000)
if not rows:
break
f.write(...)
推荐阅读
- c++ - 在 O(n) 中查找字符串的所有循环排列
- javascript - JS Javascript - 如何通过索引将数组值放入另一个数组中?
- c - c程序的意外输出
- python - Python 当匹配两列时
- javascript - Stencil、外部库、require 未定义,如何解决?
- awk - 使用 sed 或 awk 使用日期搜索循环遍历文本文件
- android - 如何克服使用文件预览器 url 打开文件 url 时自动下载文件的 android 行为?
- java - 哪个更有效率?java创建的视图还是xml中的视图?
- typescript - 为什么输入`记录
` 不接受具有已定义键的对象作为值 - identityserver4 - 桌面应用程序 - Identity Server 4 - HTTP 400 状态错误