【问题标题】:How do I recover from error in a transaction with psycopg2?如何从与 psycopg2 的事务中的错误中恢复?
【发布时间】:2017-11-21 10:30:16
【问题描述】:

我有一个从旧数据库导入数据的脚本。一路上我遇到了独特的约束违规。我想修改查询并再次执行它,但它说,“psycopg2.InternalError:当前事务被中止,命令被忽略,直到事务块结束”:

try:
    pcur.execute(sql, values)
except psycopg2.IntegrityError:
    value = ...
    pcur.execute(sql, values)

如何在不切换到自动提交模式的情况下做到这一点?

【问题讨论】:

    标签: postgresql python-3.x transactions psycopg2


    【解决方案1】:

    灵感来自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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-15
      • 2017-07-27
      • 1970-01-01
      • 2017-03-19
      • 2021-02-13
      • 2012-01-21
      • 1970-01-01
      • 2022-01-10
      相关资源
      最近更新 更多