如何加快Pandas .to_sql功能?

时间:2018-12-21 18:39:41

标签: python database oracle pandas dataframe

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函数?将一个包含1000行的120kb文件作为数据帧写入数据库需要20分钟。列类型都是VARCHAR2(256)。

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

1 个答案:

答案 0 :(得分:0)

这里发生的是,对于您插入的每一行,它必须等待事务完成才能开始下一行。解决方法是使用加载到内存中的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

相关问题