我正在尝试将pandas to_sql与几个事务一起使用,以便如果to_sql调用中的任何一个失败,那么所有这些都将被回滚。我的测试代码是:
import pandas as pd
import sqlalchemy
data = {'col1': ['val1', 'val2'],
'col2': ['val3', 'val4']}
df = pd.DataFrame(data, columns=['col1', 'col2'])
engine_pg = sqlalchemy.create_engine('postgresql://user:pass@localhost:5432/postgres')
engine_ora = sqlalchemy.create_engine('oracle://user:pass@localhost:1521/orcl', max_identifier_length=128)
conn_pg = engine_pg.connect()
conn_ora = engine_ora.connect()
trans_pg = conn_pg.begin()
trans_ora = conn_ora.begin()
try:
df.to_sql('table', conn_pg, schema='public', if_exists='replace', index=False)
df.to_sql('table', conn_ora, schema='user', if_exists='replace', index=False) #1
trans_pg.commit() #2
trans_ora.commit()
except Exception:
trans_pg.rollback()
trans_ora.rollback()
这似乎可以与Postgres一起使用,但不能与Oracle一起使用。按预期在#2提交后在Postgres中创建表,但是在#1处已经创建了Oracle表。
为什么Oracle在提交事务之前创建表?据我所知,没有在服务器端设置自动提交。
这是对熊猫to_sql使用事务的正确方法吗?可能不是,因为如果我要在同一连接上进行2个事务,那将不起作用,因为to_sql将连接作为参数而不是事务作为参数。