比如下面这两个有区别吗?
session = Session() # Session is a session maker
try:
# do some work
session.commit()
except:
session.rollback()
finally:
session.close()
和
session = Session()
try:
# do some work
session.commit()
finally:
session.close()
后者是我过去所做的,因为我假设在提交之前关闭 session (以防出错)与回滚具有相同的效果。但是我看到了第一种形式here .
最佳答案
Closing session 将隐式回滚当前事务状态:
The
close()
method issues aexpunge_all()
, and releases any transactional/connection resources. When connections are returned to the connection pool, transactional state is rolled back as well.
但我认为第一种形式更好,因为 explicit is better than implicit . SQLAlchemy 的作者也seems to reflect this sentiment .
关于python - 关闭 SQLAlchemy ORM session 是否会回滚未提交的更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46802739/