psycopg2 中的事务支持

Noo*_*bie 5 postgresql psycopg2

我对阅读psycopg2文档关于它如何处理事务(除了使用它与with语句)感到有点困惑。

通读文档我明白了

默认情况下,Psycopg 在执行第一个命令之前打开一个事务:如果不调用 commit(),任何数据操作的效果都将丢失。

假设上述陈述是正确的

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"
Run Code Online (Sandbox Code Playgroud)

对于数据的操纵ab就会迷失方向

但据我所知,这在 PostgreSQL 上并没有发生。我肯定在这里错过了一些东西,但现在我不确定什么以及在哪里。

Lau*_*lbe 4

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

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

使用类似的语句

print(dbconn.autocommit)
Run Code Online (Sandbox Code Playgroud)

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

要更改属性,只需使用

dbconn.autocommit = False
Run Code Online (Sandbox Code Playgroud)