【发布时间】:2012-11-11 10:18:20
【问题描述】:
我编写了下面的代码来处理整个应用程序中的嵌套事务。但是当它回滚一次之后,所有事务都会回滚,直到我重新启动应用程序。
# method_a starts a transaction and calls method_b
def method_a():
session.begin(subtransactions=True)
try:
method_b()
session.commit() # transaction is committed here
except:
session.rollback() # rolls back the transaction
# method_b also starts a transaction, but when
# called from method_a participates in the ongoing
# transaction.
def method_b():
session.begin(subtransactions=True)
try:
session.add(SomeObject('bat', 'lala'))
session.commit() # transaction is not committed yet
except:
session.rollback() # rolls back the transaction, in this case
# the one that was initiated in method_a().
# create a Session and call method_a
session = Session(autocommit=True)
global session
method_a(session)
【问题讨论】:
-
您使用的是哪个引擎?
-
将
except:替换为except SomeSpecificExceptionClass:。except:捕获所有错误,而您可能只想捕获数据库引发的某些特定错误。 -
我用的是mysql InoDB存储引擎
标签: python transactions python-2.7 sqlalchemy