Python DB API - commit() v. execute("commit transaction")?
Chris Angelico
rosuav at gmail.com
Tue May 30 10:21:52 EDT 2017
On Wed, May 31, 2017 at 12:12 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Tue, May 30, 2017 at 7:29 AM, Skip Montanaro
> <skip.montanaro at gmail.com> wrote:
>> Assuming the underlying database supports transactions, is there any
>> difference between calling the commit() method on the connection and
>> calling the execute method on the cursor with the "commit transaction"
>> statement? It seems a bit asymmetric to me to start a transaction with
>>
>> cur.execute("begin transaction")
>>
>> but end it with
>>
>> conn.commit()
>
> 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)
Not sure how many connectors that works with, but it's the best way to
use psycopg2.
ChrisA
More information about the Python-list
mailing list