[英]Postgres: cursor.execute(“COMMIT”) vs. connection.commit()
I am running a postgres 9.2 server and have a python client using psycopg 2.5. 我正在运行一个postgres 9.2服务器,并使用psycopg 2.5有一个python客户端。
I ran some tests because I experience a lot of WARNING: there is no transaction in progress
entries in my log files. 我运行了一些测试,因为我经历了很多
WARNING: there is no transaction in progress
我的日志文件中WARNING: there is no transaction in progress
条目。
I have some code that can be simplified to the following: 我有一些代码可以简化为以下内容:
import psycopg2
connection = psycopg2.connect(...)
with connection.cursor() as cursor:
# Multiple insert statements
cursor.execute("INSERT INTO ...")
cursor.execute("COMMIT")
What I found that if I do the following, as soon as the first COMMIT
is run (I reuse the same connection, so the above code is run multiple times) every statement afterwards is instantly committed. 我发现如果我执行以下操作,一旦第一个
COMMIT
运行(我重用相同的连接,所以上面的代码多次运行),之后的每个语句都会立即提交。 However, if I instead run connection.commit()
it works as expected (commit statements made so far, future statements will not be committed automatically). 但是,如果我改为运行
connection.commit()
它将按预期工作(到目前为止所做的提交语句,将来的语句不会自动提交)。
Is this a bug or is there some fine distinction I have missed somewhere in how this works? 这是一个错误还是有一些很好的区别我错过了它的工作原理? Is this a postgres issue or something to do with the innards of psycopg2?
这是一个postgres问题还是与psycopg2的内脏有关?
Thanks in advance! 提前致谢!
Yes, there is a not so fine distinction (documented both in the DBAPI PEP and in psycopg documentation). 是的,有一个不太好的区别(在DBAPI PEP和psycopg文档中都有记录)。 All Python DBAPI-compliant adapters implicitly start a transaction when the first SQL statement is issued through the connection.
当通过连接发出第一个SQL语句时,所有兼容Python DBAPI的适配器都会隐式启动事务。 Then you should not execute a rollback/commit directly but instead use the methods available on the
connection
object. 然后,您不应该直接执行回滚/提交,而是使用
connection
对象上可用的方法。
If you want to do your own transaction management just put the connection in autocommit mode and then send your own BEGIN, followed by other statements and ended by the usual COMMIT or ROLLBACK. 如果你想进行自己的事务管理,只需将连接置于自动提交模式,然后发送自己的BEGIN,然后发送其他语句,并以通常的COMMIT或ROLLBACK结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.