【发布时间】:2013-06-05 04:44:17
【问题描述】:
# I've set echo=True when doing create_engine, so I can see all the sql stmt
# DBSession is ScopeSession(thread_local) and autocommit is False
session = DBSession()
session.add(somemodel)
#
try:
session.flush()
raise Exception()
session.commit()
except SQLAlchemyError as e:
session.rollback()
finally:
session.close()
根据 SQLAlchemy 文档:
The close() method issues a expunge_all(), and releases any transactional/connection
resources. When connections are returned to the connection pool, transactional state is
rolled back as well.
我希望在执行“session.close()”时看到日志“回滚”
【问题讨论】:
-
为什么?除非您明确告诉数据库提交,否则不会提交事务。因此,关闭数据库连接或启动新事务会隐式回滚。
-
一个事务也隐式开始,但我可以看到日志“开始”
-
我说的是数据库级别,而不是 SQLAlchemy 级别。 SQLAlchemy 在那里显式地启动事务,结束任何以前的事务。
标签: python session sqlalchemy