Python DB API - commit() v. execute("commit transaction")?

Chris Angelico rosuav at gmail.com
Tue May 30 12:04:41 EDT 2017


On Wed, May 31, 2017 at 1:59 AM, MRAB <python at mrabarnett.plus.com> wrote:
> On 2017-05-30 16:03, Jon Ribbens wrote:
>>
>> On 2017-05-30, Joseph L. Casale <jcasale at activenetwerx.com> wrote:
>>>>
>>>> There's no difference I'm aware of in the implementations I've used,
>>>> but having a consistent API does allow for constructions such as:
>>>>
>>>> try:
>>>>     do_stuff(conn)
>>>> except:
>>>>     conn.rollback()
>>>> finally:
>>>>     conn.commit()
>>>
>>>
>>> So you always commit even after an exception?
>>
>>
>> Well, as you can see, it rollbacks then commits, so the commit does
>> nothing.
>>
> It also swallows any exception from do_stuff.

It's just missing the "raise" at the bottom of the except block. For
production code, I would assume that that would be present.

But this is why you really need to be using a context manager. If the
connector doesn't itself support them, wrap up your transaction
handling into your own context manager and use that. It's too easy to
forget something.

ChrisA



More information about the Python-list mailing list