Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres: cursor.execute("COMMIT") vs. connection.commit()

I am running a postgres 9.2 server and have a python client using psycopg 2.5.

I ran some tests because I experience a lot of WARNING: there is no transaction in progress entries in my log files.

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. However, if I instead run connection.commit() it works as expected (commit statements made so far, future statements will not be committed automatically).

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?

Thanks in advance!

like image 767
Christian P. Avatar asked May 06 '14 13:05

Christian P.


People also ask

What does Conn commit () do?

commit() Method. This method sends a COMMIT statement to the MySQL server, committing the current transaction. Since by default Connector/Python does not autocommit, it is important to call this method after every transaction that modifies data for tables that use transactional storage engines.

How does commit work in PostgreSQL?

PostgreSQL commit is used to save the transaction changes to the database, which the user made. The default value of commit is ON in PostgreSQL, which means we need not have to execute a commit statement to save the transaction; it will automatically save the transaction into the database.

How do you commit to a Postgres in Python?

If you want to commit all changes to the PostgreSQL database permanently, you call the commit() method. And in case you want to cancel the changes, you call the rollback() method. Closing the connection object or destroying it using the del will also result in an implicit rollback.


1 Answers

Yes, there is a not so fine distinction (documented both in the DBAPI PEP and in psycopg documentation). All Python DBAPI-compliant adapters implicitly start a transaction when the first SQL statement is issued through the connection. Then you should not execute a rollback/commit directly but instead use the methods available on the connection object.

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.

like image 189
fog Avatar answered Nov 04 '22 15:11

fog