Handling transactions in Python DBI module

Frank Millman frank at chagford.com
Thu Feb 11 00:28:47 EST 2016


"Chris Angelico"  wrote in message 
news:CAPTjJmphJvtCKUB6Qr-vp_1epEWxBgQxmfKEPMOhQp3pAPGG+A at mail.gmail.com...
>
> When I advise my students on basic databasing concepts, I recommend
> this structure:
>
> conn = psycopg2.connect(...)
>
> with conn, conn.cursor() as cur:
>     cur.execute(...)
>

Does this automatically issue a 'conn.commit()' on exit?

I have found that this is important, for the following reason.

If you issue a bare SELECT to PostgreSQL, it executes it without creating 
any locks. However, if it is inside a transaction, it does create a lock (I 
forget exactly which one).

Because psycopg2 silently executes 'BEGIN TRANSACTION', your SELECTs always 
happen inside a transaction whether you specify it or not. If you do not 
issue a conn.commit(), the locks do not get cleared.

Frank




More information about the Python-list mailing list