Reputation: 437
Which is the best pattern to make a query with psycopg2?
This one:
# get_connection is a function that returns a connection to the db.
with get_connection() as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT * FROM test_table")
or simply this:
with get_connection() as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM test_table")
Upvotes: 5
Views: 1490
Reputation: 3023
You can now use with
for psycopg2 connections and cursors, starting with version 2.5. The documentation is here.
It mentions:
When a connection exits the with block, if no exception has been raised by the block, the transaction is committed. In case of exception the transaction is rolled back.
Therefore, I think your first code snippet above using the nested with
blocks is the better pattern.
Upvotes: 4
Reputation: 437
It seems that psycopg2 objects don't implement the __exit__ function, so they can't be used to declare a with block!
Upvotes: 0