【问题标题】:How to insert into a SQL table from Python in splitted branches如何在拆分分支中从 Python 插入 SQL 表
【发布时间】:2021-09-02 09:01:06
【问题描述】:

我目前正在做一个关联规则项目,这是我第一次使用 SQL Server。我有一个包含所有结果的 Pandas 数据框,并希望将它们传输到 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 行?

我愿意接受其他建议。

谢谢!

【问题讨论】:

标签: python sql sql-server pandas insert


【解决方案1】:

如果您使用 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)

【讨论】:

  • 感谢您的帮助!不幸的是,这并没有解决问题。插入 1000 行(和 4 列)需要 40 秒,即使我使用函数的 chunk 参数。
猜你喜欢
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多