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

Question:

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.

Asked By: MarcinSzyc

||

Answers:

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 […]

Answered By: klin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.