使用 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/