- Symptom
- psycopg.OperationalError: the connection is closedA module-level connection fails on its second use after a with block
- Cause
- In psycopg2 the with block on a connection only ended the transaction. In psycopg 3 leaving the block closes the connection.
- Fix
- Use conn.transaction() for transaction scope and keep long-lived connections outside a with block, or use psycopg_pool.
- Apply
conn = psycopg.connect(DSN) with conn.transaction(): conn.execute("INSERT INTO t VALUES (1)") # conn is still open here- Affected
- psycopg 3.x, when porting code from psycopg2
- Sources
Last verified 2026-10-15 · Confirmed by 0 builders