如何在分割的分支中从Python插入SQL表



我目前正在做一个关联规则项目,这是我第一次使用SQL Server。我有一个包含所有结果的Pandas Dataframe,并希望将它们传输到SQL表。

但是,数据框的形状是(1788020,4),当运行代码时,它花费的时间太长,并且在500行时停止。

为了以防万一,下面是我使用的代码:

cursor2 = conn2.cursor()
cursor2.execute("truncate table APriori_test")
for index, row in dataset.iterrows():
cursor2.execute("INSERT INTO APriori_test(antecedents,consequents,support,confidence) values (?,?,?,?)",row.antecedents,row.consequents,row.support,row.confidence)
conn2.commit()

但是,当我一次只插入1000行时,它运行得很顺利,没有任何问题。

我如何自动设置插入数据的分支,例如10000行每次?

我愿意接受其他建议。

谢谢!

如果您正在使用pandas,您可能会发现有用的sqlalchemy + pandas. dataframe .to_sql。我从来没有在SQL Server中使用过它,但你的代码应该是这样的:

import pandas as pd
# you have to import your driver, e.g. import pyodbc
from sqlalchemy import create_engine
# replace with your connection string
engine = create_engine("dialect+driver://username:password@host:port/database")
df = pd.DataFrame({'A': [1,2,3], 'B':[4,5,6]})
df.to_sql('MyTable', con=engine, if_exists='append', index=False)