Question

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")
Was it helpful?

Solution 2

It seems that psycopg2 objects don't implement the __exit__ function, so they can't be used to declare a with block!

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top