我正在使用 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/