Eug*_*ash 6 python postgresql transactions psycopg2 python-db-api
如何检查psycopg2连接上的打开事务?我打算将它添加到我的单元/功能测试中,因为 Python 的 DB API 使用隐式事务。
您可以检查连接的status属性:
from psycopg2.extensions import STATUS_BEGIN, STATUS_READY
if conn.status == STATUS_READY:
print("No transaction in progress.")
elif conn.status == STATUS_BEGIN:
print("A transaction is in progress.")
Run Code Online (Sandbox Code Playgroud)
或者,可以通过以下方式获取交易状态connection.get_transaction_status()。
要手动检查正在进行的事务,您可以使用 PostgreSQL 的统计收集器:
SELECT * FROM pg_stat_activity WHERE state = 'idle in transaction';
Run Code Online (Sandbox Code Playgroud)