gpt4 book ai didi

python - 如何在 SQLAlchemy 中的 python 中回滚 dataframe.to_sql?

转载 作者:行者123 更新时间:2023-12-05 00:55:49 26 4
gpt4 key购买 nike

engine = create_engine('postgresql://username:password@host:5432/database')
transactions.to_sql('transactions', engine,if_exists='append',index=False,method='multi')

如何回滚?

最佳答案

您可以在调用 to_sql 之前开始事务,然后再进行回滚:

import pandas as pd
import sqlalchemy as sa

engine = sa.create_engine("mssql+pyodbc://@mssqlLocal64")

def dump_tran_test_table(conn):
print(conn.execute(sa.text("SELECT * FROM tran_test")).fetchall())

# set up test environment
with engine.begin() as conn:
conn.exec_driver_sql("DROP TABLE IF EXISTS tran_test")
conn.exec_driver_sql(
"CREATE TABLE tran_test "
"(txt varchar(10), id int primary key)"
)
conn.exec_driver_sql(
"INSERT INTO tran_test (txt, id) VALUES "
"('old_foo', 1), ('old_bar', 2)"
)

# test
with engine.connect() as conn:
tran = conn.begin()
df = pd.DataFrame([("new_baz", 3)], columns=["txt", "id"])
df.to_sql("tran_test", conn, index=False, if_exists="append")
dump_tran_test_table(conn)
"""console output:
[('old_foo', 1), ('old_bar', 2), ('new_baz', 3)]
"""
tran.rollback()
dump_tran_test_table(conn)
"""console output:
[('old_foo', 1), ('old_bar', 2)]
"""

关于python - 如何在 SQLAlchemy 中的 python 中回滚 dataframe.to_sql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63440779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com