【问题标题】:How to speed up Pandas .to_sql function? [duplicate]如何加速 Pandas .to_sql 函数? [复制]
【发布时间】:2019-05-22 04:47:09
【问题描述】:
import cx_Oracle
import pandas as pd
from sqlalchemy import create_engine

# credentials
username = "user"
password = "password"
connectStr = "ip:port/service_name"

df = pd.read_csv("data.csv")

# connection
dsn = cx_Oracle.makedsn('my_ip',service_name='my_service_name')

engine = create_engine('oracle+cx_oracle://%s:%s@%s' % (username, 
password, dsn))

# upload dataframe to ORCLDB
df.to_sql(name="test",con=engine, if_exists='append', index=False)

如何加快 Pandas 中的 .to_sql 函数?我花了 20 分钟将 1,000 行的 120kb 文件作为数据帧写入数据库。列类型都是 VARCHAR2(256)。

数据库列:https://imgur.com/a/9EVwL5d

【问题讨论】:

标签: python database oracle pandas dataframe


【解决方案1】:

这里发生的情况是,对于您插入的每一行,它必须等待事务完成才能开始下一个事务。这里的工作是使用加载到内存中的 CSV 文件执行“批量插入”。我知道这是如何使用 postgres(我正在使用的)完成的,但对于 oracle,我不确定。这是我用于 postgres 的代码,也许会有所帮助。

def bulk_insert_sql_replace(engine, df, table, if_exists='replace', sep='\t', encoding='utf8'):

    # Create Table
    df[:0].to_sql(table, engine, if_exists=if_exists, index=False)
    print(df)

    # Prepare data
    output = io.StringIO()
    df.to_csv(output, sep=sep, index=False, header=False, encoding=encoding)
    output.seek(0)

    # Insert data
    connection = engine.raw_connection()
    cursor = connection.cursor()
    cursor.copy_from(output, table, sep=sep, null='')
    connection.commit()
    cursor.close()

这是另一个线程的链接,其中包含有关此问题的大量重要信息:Bulk Insert A Pandas DataFrame Using SQLAlchemy

【讨论】:

    猜你喜欢
    • 2017-05-24
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 2021-01-07
    • 2018-04-09
    • 2020-04-14
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多