MarcinSzyc
MarcinSzyc

Reputation: 59

"with psycopg2.connect" is it clossing connection automatically?

I am using psycopg2 library to handle connection with Postgress database.

Are the following two approaches to handling db connection comparable?

Snipet 1:

cnx = connect(user=<...>, password=<...>, host=<...>, database=<...>)
cursor = cnx.cursor()
cursor.execute(sql)
cnx.close()

Snipet 2:

with psycopg2.connect(user=<...>, password=<...>, host=<...>, database=<...>) as cnx:
    cursor = cnx.cursor()
    cursor.execute(sql)

I am especialy interested if using WITH automatically closes connection? I was informed that second approach is preferable because it does connection close automatically. Yet when i test it using cnx.closed it shows open connection.

Upvotes: 2

Views: 931

Answers (1)

klin
klin

Reputation: 121654

The with block tries on exit to close (commit) a transaction, not a connection. For the documentation:

Note that, unlike file objects or other resources, exiting the connection’s with block doesn’t close the connection but only the transaction associated with it [...]

Upvotes: 3

Related Questions