bjarkemoensted
bjarkemoensted

Reputation: 2776

Should I manually close a database connection if using context managing (with-as)?

I'm learning how to use a PostgreSQL database with Python (3.6)'s psycopg2 module. I'm having trouble figuring out exactly under which circumstances I should manually close my connections. According to the docs:

unlike file objects or other resources, exiting the connection’s with block doesn’t close the connection but only the transaction associated with it: a connection can be used in more than a with statement and each with block is effectively wrapped in a separate transaction

But then comes an example code snippet:

conn = psycopg2.connect(DSN)

with conn:
    with conn.cursor() as curs:
        curs.execute(SQL1)

with conn:
    with conn.cursor() as curs:
        curs.execute(SQL2)

conn.close()

However, I'm used to seeing context managing using with-as, i.e. something like

with psycopg2.connect(DSN) as conn:
    with conn.cursor() as curs:
        curs.execute(SQL)

Is this a reasonable approach, or will there still be an open connection after running the above? If so, how do I close it, since 'conn' no longer exists?

Upvotes: 1

Views: 764

Answers (1)

Sraw
Sraw

Reputation: 20224

According to official doc: http://initd.org/psycopg/docs/connection.html#connection.close

Close the connection now (rather than whenever del is executed)....

When a connection object is deleted, it will be closed. Although I didn't find related source code as they are all written in C++.

Upvotes: 2

Related Questions