python - Psycopg2:使用 with ... as 在 python 中进行查询

标签 python psycopg2 with-statement

使用 psycopg2 进行查询的最佳模式是什么?

这个:

# get_connection is a function that returns a connection to the db.
with get_connection() as conn:
    with conn.cursor() as cursor:
        cursor.execute("SELECT * FROM test_table")

or simply this:

with get_connection() as conn:
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM test_table")

最佳答案

从 2.5 版开始,您现在可以将 with 用于 psycopg2 连接和游标。文档是 here .

它提到:

When a connection exits the with block, if no exception has been raised by the block, the transaction is committed. In case of exception the transaction is rolled back.

因此,我认为您上面使用嵌套 with block 的第一个代码片段是更好的模式。

关于python - Psycopg2:使用 with ... as 在 python 中进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13346264/

相关文章:

email - python : sending a mail, 在 "with" block 内时失败

python - 使用 Pandas 数据框将一列中的对列表转换为两列

python - 无法在 Microsoft Azure 上运行 Dash 应用程序

python - Django 运行服务器错误(psycopg2)

sqlalchemy - psycopg2.操作错误: could not translate host name "<address>" to address: Temporary failure in name resolution

python - 如何使用 __enter__/__exit__ 方法对类进行单元测试?

python - 使用带有 try-except block 的 python "with"语句

python - Django ( python ): DatabaseError : x Table has No Column named y

Python 卡住应用程序文件类型

python - PostgreSQL 和 Python