是否需要在脚本末尾关闭Psycopg2连接? [英] Is it required to close a Psycopg2 connection at the end of a script?

查看:525
本文介绍了是否需要在脚本末尾关闭Psycopg2连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python脚本结束时不关闭 psycopg2 连接会有什么后果?例如,考虑以下代码段:

  import psycopg2 
psycopg2.connect( dbname = test)

该脚本打开一个连接,但最后不关闭它。执行结束时连接是否仍然打开?如果是这样,是否存在不关闭连接的问题?

解决方案

通常,当您的python程序退出时,它拥有的所有套接字将被关闭,未平仓交易中止。但是,最好在最后关闭连接。



一旦不再需要关闭连接,将会释放系统资源。

请记住,如果您确实关闭连接,请首先提交更改。如您在psycopg2 API中所读到的:


现在关闭连接(而不是在执行del时)。从现在开始,该连接将无法使用。如果尝试对连接进行任何操作,都会引发InterfaceError。这同样适用于所有尝试使用该连接的游标对象。请注意,在没有先提交更改的情况下关闭连接将导致所有待处理的更改都被丢弃,就像执行了ROLLBACK一样



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?

解决方案

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

这篇关于是否需要在脚本末尾关闭Psycopg2连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆