如何在psycopg2中回滚?

发布于 2025-01-16 06:10:57 字数 574 浏览 1 评论 0原文

我在 qry2 中强制出现错误,以便 a 可以运行 qry3,假设它可以回滚到 save_1,但事实并非如此。有什么收获吗?使用 PostgreSql 14.2

qry1 = ('begin;' +
        'savepoint save_1;' +
        'delete from ntnb_cup;')

qry2 = ...
        # Force error

qry3 = 'rollback to save_1;'

try:
    cursor = conn.cursor()
    cursor.execute(qry1)
    conn.commit()
except Exception as err:
    cursor.close()
    conn.close()
    exit()

try:
    cursor.execute(qry2)
    conn.commit()  
except Exception as err:
    cursor.execute(qry3)
    conn.commit()    
finally:
    cursor.close()
    conn.close()

I´m forcing an error in qry2 so that a can run qry3 suposing it could rollback to save_1 but it doesn´t. Any catch? Using PostgreSql 14.2

qry1 = ('begin;' +
        'savepoint save_1;' +
        'delete from ntnb_cup;')

qry2 = ...
        # Force error

qry3 = 'rollback to save_1;'

try:
    cursor = conn.cursor()
    cursor.execute(qry1)
    conn.commit()
except Exception as err:
    cursor.close()
    conn.close()
    exit()

try:
    cursor.execute(qry2)
    conn.commit()  
except Exception as err:
    cursor.execute(qry3)
    conn.commit()    
finally:
    cursor.close()
    conn.close()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

盗心人 2025-01-23 06:10:57
try:
    cursor = conn.cursor()
    cursor.execute(qry1)
    conn.commit()

一旦你承诺了,你就承诺了。要保留稍后回滚到保存点的选项,请不要在此处提交。

try:
    cursor = conn.cursor()
    cursor.execute(qry1)
    conn.commit()

Once you commit, you are committed. To preserve the option of rolling back to a savepoint later, don't commit here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文