python - "with psycopg2.connect"是否自动关闭连接?

标签 python postgresql psycopg2

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

以下两种处理数据库连接的方法是否具有可比性?

片段 1:

cnx = connect(user=<...>, password=<...>, host=<...>, database=<...>)
cursor = cnx.cursor()
cursor.execute(sql)
cnx.close()

截图2:

with psycopg2.connect(user=<...>, password=<...>, host=<...>, database=<...>) as cnx:
    cursor = cnx.cursor()
    cursor.execute(sql)

我特别感兴趣是否使用WITH会自动关闭连接?我被告知第二种方法更好,因为它会自动关闭连接。然而,当我使用 cnx.close 测试它时,它显示打开的连接。

最佳答案

with block 尝试退出以关闭(提交)事务,而不是连接。对于 the documentation:

Note that, unlike file objects or other resources, exiting the connection’s with block doesn’t close the connection but only the transaction associated with it [...]

关于python - "with psycopg2.connect"是否自动关闭连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54071880/

相关文章:

python - 复制带有 Telethon 的帖子链接

python - psycopg2:在连接到 PostgreSQL 的 Python 中显示多列数据时出错

python - Pytest 模块未找到错误

python - 在 Centos 5 上使用非系统 Openssl 编译 Python 2.7.12

postgresql - 如何检索 postgres 中两个 tsvectors 的差异?

django - 在 Django 中检索 OneToOne 相关的 QuerySet

java - 数据库查询错误。代码 : 42601 Message: syntax_error Cause: ERROR: syntax error at or near "<"

python - 使用定义变量创建表

postgresql - 导入错误 :/lib/libc. so.6 : version `GLIBC_2.14' not found (required by/usr/lib/libpq. so.5)

python - 从终端运行 python 包