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

Chris Angelico rosuav at gmail.com
Fri Jun 2 04:24:28 EDT 2017


On Fri, Jun 2, 2017 at 6:10 PM, Gregory Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> Chris Angelico wrote:
>>
>> Executing a query gives you some sort of object. That object either
>> contains all the results, or has the resource handle (or whatever)
>> needed to fetch more from the back end. That basically makes it a
>> cursor, so we're not far different after all :)
>
>
> The point is that my API doesn't make a big deal out of them.
> You don't typically think about them, just as you don't usually
> think much about the intermediate iterator created when you
> do "for x in some_list".

Which is a fully reasonable way to do things. And actually, on further
consideration, I think it's probably the better way; the number of
times you would want to explicitly create a cursor are so few that
they can be handled by some sort of unusual method call, and the basic
usage should look something like this:

with psycopg2.connect(...) as conn:
    with conn.trans() as trn:
        for row in trn.execute("select ..."):
            print(row)

The outer context manager is optional, but not the inner one and the
method call, as I'm not a fan of the unusual usage where "with conn:"
creates a transaction - it's different from the way most context
managers work (managing the resource represented by the object itself,
not some additional resource allocated on __enter__). The iterator
used on trn.execute would be a cursor such as you describe.

ChrisA



More information about the Python-list mailing list