如何从与 psycopg2 的事务中的错误中恢复?
How do I recover from error in a transaction with psycopg2?
我有一个从旧数据库导入数据的脚本。在某个地方我 运行 违反了唯一约束。我想修改查询并再次执行,但它说,"psycopg2.InternalError: current transaction is aborted, commands ignored until end of transaction block":
try:
pcur.execute(sql, values)
except psycopg2.IntegrityError:
value = ...
pcur.execute(sql, values)
如何在不切换到自动提交模式的情况下执行此操作?
灵感来自 this answer:
pcur.execute('SAVEPOINT sp1')
try:
pcur.execute(sql, values)
except psycopg2.IntegrityError:
pcur.execute('ROLLBACK TO SAVEPOINT sp1')
value = ...
pcur.execute(sql, values)
else:
pcur.execute('RELEASE SAVEPOINT sp1')
我有一个从旧数据库导入数据的脚本。在某个地方我 运行 违反了唯一约束。我想修改查询并再次执行,但它说,"psycopg2.InternalError: current transaction is aborted, commands ignored until end of transaction block":
try:
pcur.execute(sql, values)
except psycopg2.IntegrityError:
value = ...
pcur.execute(sql, values)
如何在不切换到自动提交模式的情况下执行此操作?
灵感来自 this answer:
pcur.execute('SAVEPOINT sp1')
try:
pcur.execute(sql, values)
except psycopg2.IntegrityError:
pcur.execute('ROLLBACK TO SAVEPOINT sp1')
value = ...
pcur.execute(sql, values)
else:
pcur.execute('RELEASE SAVEPOINT sp1')