Sujet : Re: psycopg2: proper positioning of .commit() within try: except: blocks
De : greg.ewing (at) *nospam* canterbury.ac.nz (Greg Ewing)
Groupes : comp.lang.pythonDate : 08. Sep 2024, 02:48:50
Autres entêtes
Message-ID : <lk4ajkFbbnrU1@mid.individual.net>
References : 1 2 3 4 5 6 7 8
User-Agent : Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:91.0) Gecko/20100101 Thunderbird/91.3.2
On 8/09/24 9:20 am, Karsten Hilbert wrote:
try:
do something
except:
log something
finally:
.commit()
cadence is fairly Pythonic and elegant in that it ensures the
the .commit() will always be reached regardless of exceptions
being thrown or not and them being handled or not.
That seems wrong to me. I would have thought the commit should only
be attempted if everything went right.
What if there's a problem in your code that causes a non-SQL-related
exception when some but not all of the SQL statements in the
transaction bave been issued? The database doesn't know something
has gone wrong, so it will happily commit a partially-completed
transaction and possibly corrupt your data.
This is how I normally do things like this:
try:
do something
.commit()
except:
log something
.rollback()
Doing an explicit rollback ensures that the transaction is always
rolled back if it is interrupted for any reason.
-- Greg