문제

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")
도움이 되었습니까?

해결책 2

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top