【问题标题】:Fast loading into SQL server with python使用 python 快速加载到 SQL Server
【发布时间】: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()

【问题讨论】:

标签: python sql-server data-science


【解决方案1】:

感谢您的回答 - 除了使用 JSON 外,我都尝试过,可能是我错了。

这是我的解决方案

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 2020-02-10
    • 1970-01-01
    • 2017-10-20
    • 2022-01-19
    • 2018-07-12
    • 1970-01-01
    相关资源
    最近更新 更多