gpt4 book ai didi

postgresql - psycopg2 中的事务支持

转载 作者:行者123 更新时间:2023-11-29 12:17:03 24 4
gpt4 key购买 nike

阅读有关它如何处理事务的 psycopg2 文档时,我有点困惑(除了将其与 with 语句一起使用)。

通读 docs , 我明白了

By default, Psycopg opens a transaction before executing the first command: if commit() is not called, the effect of any data manipulation will be lost.

假设上述说法正确

dbconn = psycopg2.connect(...)   cursor = dbconn.cursor()
cursor.execute("insert record into a")
cursor.execute("insert record into b")

cursor.execute("insert record into c") // This throw integrity error.
cursor.execute("commit") // this logs "WARNING: there is no transaction in progress"

ab 的数据操作会丢失

但在我看来,这并没有发生在 PostgreSQL 上。我肯定在这里遗漏了一些东西,但现在我不确定是什么和在哪里。

最佳答案

您必须处于自动提交模式。

警告是在没有启动显式事务时发出 COMMIT 时收到的警告(PostgreSQL 默认处于自动提交模式!)。

使用这样的语句

print(dbconn.autocommit)

验证是否启用了自动提交。

要更改属性,只需使用

dbconn.autocommit = False

关于postgresql - psycopg2 中的事务支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47833724/

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