首页 > 解决方案 > 调用 pandas to_sql() 时抑制 SQL 语句的输出

问题描述

to_sql()正在打印我的 Jupyter Notebook 中的每个插入语句,这使得数百万条记录的运行速度非常缓慢。如何显着降低冗长?我还没有找到这个函数的任何详细设置。我试过%%capture这里写的。同样的方法适用于另一个简单的测试用例,print()但不适用于to_sql(). 你如何抑制 IPython Notebook 中的输出?

from sqlalchemy import create_engine, NVARCHAR
import cx_Oracle

df.to_sql('table_name', engine, if_exists='append', 
              schema='schema', index=False, chunksize=10000,
                dtype={col_name: NVARCHAR(length=20) for col_name in df} )

标签: pandasoraclesqlalchemyjupyter-notebook

解决方案


在内部create_engine(),设置echo=False和所有日志记录都将被禁用。更多详细信息:https ://docs.sqlalchemy.org/en/13/core/engines.html#more-on-the-echo-flag 。

from sqlalchemy import create_engine, NVARCHAR
import cx_Oracle

host='hostname.net'
port=1521
sid='DB01' #instance is the same as SID
user='USER'
password='password'
sid = cx_Oracle.makedsn(host, port, sid=sid)

cstr = 'oracle://{user}:{password}@{sid}'.format(
    user=user,
    password=password,
    sid=sid
)

engine =  create_engine(
    cstr,
    convert_unicode=False,
    pool_recycle=10,
    pool_size=50,
    echo=False
)

感谢@GordThompson 为我指明了正确的方向!


推荐阅读