PostgreSQL · sdk · fg-0281

psycopg 3 'with connection' block closes the connection that psycopg2 kept open

If you see psycopg.OperationalError: the connection is closed, the cause and the fix for PostgreSQL are below, last verified 2026-10-15.

Verified Oct 2026trust 50/100
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

Related traps

Have your agent know this before it fails

$ /plugin marketplace add getfootgun/footgun
$ /plugin install footgun@footgun