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

Chris Angelico rosuav at gmail.com
Tue May 30 11:36:23 EDT 2017


On Wed, May 31, 2017 at 1:09 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Tue, May 30, 2017 at 8:21 AM, Chris Angelico <rosuav at gmail.com> wrote:
>> On Wed, May 31, 2017 at 12:12 AM, Ian Kelly <ian.g.kelly at gmail.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()
>>>
>>> without having to worry about variations in syntax between databases.
>>
>> I prefer:
>>
>> with conn, conn.cursor() as cur:
>>     do_stuff(cur)
>
> As do I, but it's not as clear what that does and the use as context
> managers is also not explicitly supported by PEP 249.

Yes, it's not very clear that "with conn, conn.cursor() as cur" means
"with the database". What I'd really like would be "with conn:", but
that's only half the story. But it does make very good sense to use a
context manager to bracket all use of the database.

ChrisA



More information about the Python-list mailing list