简体   繁体   English

是否需要在脚本末尾关闭Psycopg2连接?

[英]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? 在Python脚本结束时不关闭psycopg2连接有什么后果? 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? 如果是这样,是否存在未关闭连接的问题?

Normally when your python program exits, all the sockets it owns will be closed, and open transactions aborts. 通常当你的python程序退出时,它所拥有的所有套接字都将被关闭,并且打开的事务将中止。 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: 您可以在psycopg2 API中阅读:

Close the connection now (rather than whenever del is executed). 立即关闭连接(而不是每次执行del时)。 The connection will be unusable from this point forward; 从这一点开始,连接将无法使用; an InterfaceError will be raised if any operation is attempted with the connection. 如果尝试连接任何操作,将引发InterfaceError。 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 请注意,关闭连接而不先提交更改将导致任何挂起的更改被丢弃,就像执行ROLLBACK一样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM