【发布时间】:2019-09-24 05:15:58
【问题描述】:
我正在尝试加快将大型 CSV 文件加载到 MySQL 数据库中的速度。使用此代码加载 4GB 文件大约需要 4 小时:
with open(source) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
next(csv_reader)
insert_sql = """ INSERT INTO billing_info_test (InvoiceId, PayerAccountId, LinkedAccountId) VALUES (%s, %s, %s) """
for row in csv_reader:
cursor.execute(insert_sql,row)
print(cursor.rowcount, 'inserted with LinkedAccountId', row[2], 'at', datetime.now().isoformat())
print("Committing the DB")
mydb.commit(
cursor.close()
mydb.close()
我想使用executemany() 语句来加快速度。为此,您必须将元组列表传递给第二个参数。
如果我在每次行迭代时构建列表,它会变得太大,并且当列表变得太大时会出现内存不足错误,并且脚本会崩溃。
我无法获取 csv_reader 或 csv_file 的长度以在范围语句中使用。
如何一次遍历 CSV 文件 1000 行并将结果存储在列表中,在 executemany 中使用它,然后存储接下来的 1000 行等,直到 CSV 文件结束?
【问题讨论】:
标签: python mysql executemany