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

寵の児 提交于 2019-12-06 18:40:39

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/31240830/is-it-required-to-close-a-psycopg2-connection-at-the-end-of-a-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!