gpt4 book ai didi

python - 如果我使用带有 pyodbc 游标的上下文管理器,它会在出现错误时回滚吗?

转载 作者:行者123 更新时间:2023-11-28 21:50:16 24 4
gpt4 key购买 nike

我尝试阅读 pyodbc 源代码,但它全是 C++ 代码(我不擅长 C++)。我需要知道如下语句的行为:

 with connection.cursor() as cursor:
cursor.execute(query_1) #inserts some stuff into table A
cursor.execute(query_2) #inserts some stuff into table B, but throws an error

with connection.cursor() as cursor2:
cursor.execute(select_query_1) #selects from table A
cursor.execute(select_query_2) #selects from table B

这是在我们尚未提交的同一连接中 - 我很好奇从表 A 中选择是否会给出插入第一个游标的新值 - 或者 query_2 中的错误是否导致第一​​个游标的工作为表 A 回滚。

最佳答案

查看 source , 和 ODBC Documentation该行为部分取决于 autocommit 是启用还是禁用。

  • 如果 autocommitFalse,则第一次调用 cursor.execute() 会隐式打开一个新事务。 (见注释 1)此游标每次对 execute() 的后续调用都使用相同的事务,除非 commit()rollback() 是打电话。
  • 当 Python 离开 with block 并调用 __exit__ 时:
    • 如果autocommitFalse,并且没有错误,游标会自动提交事务。此操作的来源见注2。
    • 如果 autocommitTrue,或者如果出现错误,则游标退出而不结束事务。
  • 当游标关闭时,无论是使用 cursor.close() 还是当显式或隐式调用 __del__ 时,挂起的语句结果也会在游标内部时自动删除句柄被释放。 (注3)

如果 cursor.execute() 失败,事务仍处于打开状态,但未提交。在这种情况下,由您决定是提交还是回滚。

尽管如此,您仍然应该在目标环境中测试行为。不同的 ODBC 数据源具有不同级别的事务支持。


注1:(source)

If the data source is in manual-commit mode (requiring explicit transaction initiation) and a transaction has not already been initiated, the driver initiates a transaction before it sends the SQL statement.

注2:(pyodbc/cursor.cpp @ 2151)

// If an error has occurred, `args` will be a tuple of 3 values.  
// Otherwise it will be a tuple of 3 `None`s.
I(PyTuple_Check(args));
if (cursor->cnxn->nAutoCommit == SQL_AUTOCOMMIT_OFF && PyTuple_GetItem(args, 0) == Py_None)
...
ret = SQLEndTran(SQL_HANDLE_DBC, cursor->cnxn->hdbc, SQL_COMMIT);

注3:(source

When an application calls SQLFreeHandle to free a statement that has pending results, the pending results are deleted.

关于python - 如果我使用带有 pyodbc 游标的上下文管理器,它会在出现错误时回滚吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32128508/

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