Do I need to close the Psycopg2 connection at the end of the script?

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

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

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

+7
python postgresql psycopg2 database-connection
source share
1 answer

Usually, when your python program exits, all its sockets are closed and transactions are aborted. But it is good practice to close the connection at the very end.

Closing a connection as soon as you no longer need it frees up system resources. This is always good.

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

Close the connection now (and not whenever del is executed). The connection will be unsuitable from this point forward; when any connection operation occurs, an InterfaceError will be raised. The same applies to all cursor objects trying to use a connection. Note that closing a connection without making a change first will discard any pending changes, as if ROLLBACK were running

+4
source share

All Articles