【问题标题】:executemany() -- taking too long to INSERT csv file (~150,000 rows)executemany()——插入 csv 文件花费的时间太长(~150,000 行)
【发布时间】:2023-02-14 11:33:53
【问题描述】:

我一直在尝试使用 executemany() 将 csv 文件(~150,000 行)插入到表中。但是,当我运行该程序时,它仍然处于空闲状态,我必须使用 KeyboardInterrupt 来中断它。或者,我可以使用 forloop 和 cursor.execute() INSERT ~10,000 行,但理想情况下我想要一个允许我更有效地插入更大数据集的选项。

代码如下:

with open('data.csv','r') as csv_file:
csvfile = csv.reader(csv_file, delimiter=',')
all_value = []
for row in csvfile:
    value = (row[0], row[1], row[2], row[3], row[4], row[5])
    all_value.append(value)

query = ("INSERT INTO lane_data (carrier, origin_zip, dest_zip, act_transit_days, est_transit_days, loads) "
            "VALUES (%s, %s, %s, %s, %s, %s)")


cursor.executemany(query, all_value)

【问题讨论】:

  • 您可能需要批处理您的提交,例如插入 20000 条记录,提交,重复。单个巨大的提交可能会使用过多的内存。

标签: csv mysql-python executemany mysql-connector-c


【解决方案1】:

我遇到了同样的问题,我最好的选择是使用 BULK INSERT(在我的例子中是 MSSQL)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多