Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it required to close a Psycopg2 connection at the end of a script?

What are the consequences of not closing a psycopg2 connection at the end of a Python script? For example, consider the following snippet:

import psycopg2
psycopg2.connect("dbname=test")

The script opens a connection, but does not close it at the end. Is the connection still open at the end of the execution? If so, is there an issue with not closing the connection?

like image 404
Marco Avatar asked Jul 06 '15 08:07

Marco


People also ask

Does Psycopg2 close connection automatically?

Changed in version 2.5: if the connection is used in a with statement, the method is automatically called if no exception is raised in the with block. Roll back to the start of any pending transaction. Closing a connection without committing the changes first will cause an implicit rollback to be performed.

Is Psycopg2 connection thread safe?

Thread and process safetyThe Psycopg module and the connection objects are thread-safe: many threads can access the same database either using separate sessions and creating a connection per thread or using the same connection and creating separate cursors.

Is Psycopg2 asynchronous?

Asynchronous notificationsPsycopg allows asynchronous interaction with other database sessions using the facilities offered by PostgreSQL commands LISTEN and NOTIFY .


1 Answers

Normally when your python program exits, all the sockets it owns will be closed, and open transactions aborts. But it's good practice to close the connection at the very end.

Closing a connection as soon as you don't need it anymore results in freeing system resources. Which is always good.

Keep in mind that if you do close your connection, to first commit your changes. As you can read in the psycopg2 API:

Close the connection now (rather than whenever del is executed). The connection will be unusable from this point forward; an InterfaceError will be raised if any operation is attempted with the connection. The same applies to all cursor objects trying to use the connection. Note that closing a connection without committing the changes first will cause any pending change to be discarded as if a ROLLBACK was performed

like image 134
DJanssens Avatar answered Sep 21 '22 17:09

DJanssens