Pandas DataFrame.to_sql() 不再使用 sqlalchemy 2.0.1 engine.connect() 作为上下文管理器,并且不会抛出任何错误

s.k*_*s.k 2 python sqlalchemy psycopg2 contextmanager pandas

这段带有pandas 1.5.3sqlalchemy 的 2.0.1代码不再工作,令人惊讶的是,它不会引发任何错误,代码默默地通过:

# python 3.10.6
import pandas as pd # 1.5.3
import psycopg2 # '2.9.5 (dt dec pq3 ext lo64)'
from sqlalchemy import create_engine # 2.0.1


def connector():
    return psycopg2.connect(**DB_PARAMS)

engine = create_engine('postgresql+psycopg2://', creator=connector)

with engine.connect() as connection:
    df.to_sql(
        name='my_table',
        con=connection,
        if_exists='replace',
        index=False,
    )
Run Code Online (Sandbox Code Playgroud)

目前,使用 sqlalchemy,2.0.1我的表不再填充 DataFrame 内容。

而它已正确填充 sqlalchemy version 1.4.45

编辑

显然,当我使用上下文管理器时它会起作用:

connection = engine.connect()

res.to_sql(
    name='my_table',
    con=connection,
    if_exists='replace',
    index=False
)
Out[2]: 133 # <- wondering what is this return code '133' here?

connection.commit()
connection.close()
Run Code Online (Sandbox Code Playgroud)

我怎样才能让它与上下文管理器(又名with声明)一起工作?

sna*_*erb 11

您正在使用的上下文管理器会在退出时回滚。相反,使用engine.begin(),它将提交。

with engine.begin() as connection:
    df.to_sql(
        name='my_table',
        con=connection,
        if_exists='replace',
        index=False,
    )
Run Code Online (Sandbox Code Playgroud)