[DB-SIG] Use of context managers with DB API 2
Vernon Cole
vernondcole at gmail.com
Fri Nov 2 15:28:47 CET 2012
Christoph, I think you may be Dutch -- your design proposal feels right to
me.
(+1) from Vernon
On Fri, Nov 2, 2012 at 3:53 AM, Christoph Zwerschke <cito at online.de> wrote:
>
> What I find a bit ugly about this approach is that now the context
> managers of connections and cursors behave differently, and that code
> written using these context managers is not self-explanatory. If
> connections and cursors would just have closing context managers, and
> connections had an extra "transaction" member that is a context manager for
> handling the transaction, the code would be more readable and explicit
> which is better than implicit:
>
> with dbapi2.connect(...) as con:
> with con.transaction:
> with con.cursor() as cur:
> cur.execute("insert into debit(amount) values (-100)")
> cur.execute("insert into credit(amount) values (100)")
> with con.transaction:
> with con.cursor() as cur:
> cur.execute("insert into debit(amount) values (-200)")
> cur.execute("insert into credit(amount) values (200)")
>
> Or, when using the shortcut methods:
>
> with dbapi2.connect(...) as con:
> with con.transaction:
> con.execute("insert into debit(amount) values (-100)")
> con.execute("insert into credit(amount) values (100)")
> with con.transaction:
> con.execute("insert into debit(amount) values (-200)")
> con.execute("insert into credit(amount) values (200)")
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/db-sig/attachments/20121102/02827621/attachment.html>
More information about the DB-SIG
mailing list