A
A
AlmazKayum2022-03-03 13:46:19
Python
AlmazKayum, 2022-03-03 13:46:19

Do I need to put a commit in the with construct?

Python 3.7.3
PostgreSQL 10

import psycopg2

class User:

    def __init__(self, database):
        self.conn = psycopg2.connect(database)
        self.cursor = self.conn.cursor()

    def set_address(self, address, user_id):
        with self.conn:
            self.cursor.execute('UPDATE users SET address=%s WHERE user_id=%s', (user_id, address))
            self.conn.commit()

The with construct seems to imply closing the database connection, should I put self.conn.commit() ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2022-03-05
@galaxy

The with clause seems to imply closing the database connection.

does not include :
Cursors can be used as context managers: leaving the context will close the cursor.

The connection only closes the close() method of the connection object (or del on the connection).
Do commit() in your case is necessary, because. by default, psycopg opens a transaction before executing the first request. Another option is to work in autocommit mode .
In general, for the future, constructions with with do different things in different DBMS drivers and are not regulated by DB-API. So you need to either carefully smoke the documentation, or not use them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question