【发布时间】:2021-11-21 16:28:20
【问题描述】:
我有一个包含六列和大约 27000 行的数据框。
我正在尝试将此数据帧加载到我的 SQL Server(不是本地主机)中,但这需要很长时间。
有谁知道比这更快的加载方式 -
27000 行不应该花很长时间。
从数据库读取时没有问题。 :-)
for index, row in predict.iterrows():
params = [(row.account_no, row.group_company, row.customer_type, row.invoice_date, row.lower, row.upper)]
cursor.fast_executemany = True
cursor.executemany("INSERT INTO ML.predictions (account_no,group_company,customer_type,invoice_date,lower, upper) values(?,?,?,?,?,?)",
params)
bachelor.commit()
回答
records = [str(tuple(x)) for x in predict.values]
insert_ = """
INSERT INTO ml.predictions(account_no, group_company, customer_type, invoice_date, lower, upper) VALUES
"""
def chunker(seq, size):
return (seq[pos:pos + size] for pos in range(0, len(seq), size))
for batch in chunker(records, 1000):
rows = ','.join(batch)
insert_rows = insert_ + rows
cursor.execute(insert_rows)
bachelor.commit()
【问题讨论】:
-
这里的“永远”是什么?
-
你的缩进搞砸了,所以不清楚循环内是否有
commit()或者这是否是一个错字。如果它在循环中,那么您的问题是矛盾的 - 您正在使用批量插入方法插入单行 -
您可以使用 JSON 将批量数据传递到 SQL Server。见stackoverflow.com/questions/60745932/…
标签: python sql-server data-science