我正在尝试使用原始sqlalchemytext()查询将值插入Postgres11数据库。通过psql- client运行以下SQL查询时,它可以正常运行:
text()
WITH a AS ( INSERT INTO person (id) VALUES ('a') RETURNING id ) INSERT INTO person_info (person_id) SELECT id FROM a;
所有行均正确插入:
# select id from person; id ---- a (1 row)
但是,如果我在sqlalchemy中创建一个引擎,并使用相同的查询在其上调用execute,它会成功运行,但不会插入任何行:
>>> engine.execute("WITH a AS (INSERT INTO person (id) VALUES ('b') RETURNING id) INSERT INTO person_info (person_id) SELECT id from a") <sqlalchemy.engine.result.ResultProxy object at 0x7f25e6c2a090>
但是没有插入新行:
通过psql-client运行查询与通过sqlalchemy执行查询有何不同?
我的问题在github上得到了回答。
解决方案是将执行包装在事务上下文中:
with engine.begin() as conn: conn.execute("whatever")