gpt4 book ai didi

python - 上下文管理器、多个函数调用和事务

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:37 24 4
gpt4 key购买 nike

说我愿意:

with my_connection:
o.first_call()

其中 my_connection__exit__ 方法调用回滚

o.first_call在其执行中调用j.second_call,后者本身又调用z.third_call。假设 z.third_call 成功将一条记录插入数据库,j.second_call 也成功插入一条记录,但 o.first_call 崩溃了。我会回滚到第一次进入 my_connection 上下文之前的状态,还是会回滚到 o.first_callj.second_call 之间的状态?

编辑:要明确的是,我希望整个事情能够回滚到我调用 o.first_call

之前

EDIT2:我希望如果有一些魔法我可以在 __enter__ 中实现,某种上下文可以说,无论调用什么都是一笔大交易。

最佳答案

事务将回滚到最后一次commit调用。

Database API Specification v2.0 :

.commit()

Commit any pending transaction to the database.

.rollback()

... causes the database to roll back to the start of any pending transaction.

所以这取决于你所说的“成功插入”是什么意思。如果插入是通过调用 commit 完成的,则回滚将不会删除插入。但是,如果没有提交,则插入将回滚。

关于python - 上下文管理器、多个函数调用和事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22899271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com