你可以做一个rollback
的交易或只是引发异常(cr为光标)的代码之前回滚到一个保存点:
name = uuid.uuid1().hex
cr.execute('SAVEPOINT "%s"' % name)
try:
# your failing query goes here
except Exception:
cr.execute('ROLLBACK TO SAVEPOINT "%s"' % name)
# your alternative code goes here
else:
cr.execute('RELEASE SAVEPOINT "%s"' % name)
此代码假定存在正在运行的事务,否则你不会收到该错误信息。
Django的PostgreSQL后端creates cursors直接从psycopg。也许在将来他们会为Django光标创建一个代理类,类似于cursor of odoo。他们延长光标与following code(自我是光标):
@contextmanager
@check
def savepoint(self):
"""context manager entering in a new savepoint"""
name = uuid.uuid1().hex
self.execute('SAVEPOINT "%s"' % name)
try:
yield
except Exception:
self.execute('ROLLBACK TO SAVEPOINT "%s"' % name)
raise
else:
self.execute('RELEASE SAVEPOINT "%s"' % name)
这样的背景使代码更容易,这将是:
try:
with cr.savepoint():
# your failing query goes here
except Exception:
# your alternative code goes here
而且代码的可读性,因为交易的东西不存在。
这不会起作用,当发生错误时,事务被中止并回滚。数据库中需要一个异常处理程序。 查询失败:错误:当前事务中止,忽略命令直到事务块结束 – 2010-03-03 18:38:11
是的。这就是SAVEPOINTs的重点。为了给出一个具体的例子,我编辑了我的答案。 – 2010-03-03 19:02:02
----编辑---- 对不起,我错了...对我感到羞耻;)它工作正常,你说得对。 – 2010-03-03 19:06:07