Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python &引用;使用psycopg2.connect“;它是否自动关闭连接?_Python_Postgresql - Fatal编程技术网

Python &引用;使用psycopg2.connect“;它是否自动关闭连接?

Python &引用;使用psycopg2.connect“;它是否自动关闭连接?,python,postgresql,Python,Postgresql,我正在使用psycopg2库处理与Postgress数据库的连接 以下两种处理db连接的方法是否具有可比性 狙击手1: cnx = connect(user=<...>, password=<...>, host=<...>, database=<...>) cursor = cnx.cursor() cursor.execute(sql) cnx.close() cnx=connect(用户=、密码=、主机=、数据库=) cursor=cnx.

我正在使用psycopg2库处理与Postgress数据库的连接

以下两种处理db连接的方法是否具有可比性

狙击手1:

cnx = connect(user=<...>, password=<...>, host=<...>, database=<...>)
cursor = cnx.cursor()
cursor.execute(sql)
cnx.close()
cnx=connect(用户=、密码=、主机=、数据库=)
cursor=cnx.cursor()
cursor.execute(sql)
cnx.close()
狙击手2:

with psycopg2.connect(user=<...>, password=<...>, host=<...>, database=<...>) as cnx:
    cursor = cnx.cursor()
    cursor.execute(sql)
使用psycopg2.connect(用户=,密码=,主机=,数据库=)作为cnx:
cursor=cnx.cursor()
cursor.execute(sql)

我特别感兴趣,如果使用自动关闭连接?我被告知第二种方法更可取,因为它不会自动关闭连接。然而,当我使用cnx.closed测试它时,它显示打开的连接。

with块在退出时尝试关闭(提交)事务,而不是连接。为了

请注意,与文件对象或其他资源不同,退出连接的with块不会关闭连接,而只关闭与其关联的事务[…]


您在什么时候使用的是
cnx.closed