[DB-SIG] DB API extension suggestion
Robert Brewer
fumanchu at amor.org
Thu Jun 21 19:20:49 CEST 2007
Anthony Tuininga wrote:
> I have been recently playing with context managers and the new "with"
> statement added in Python 2.5. I would like to suggest the addition of
> the following methods to connections:
>
> def __enter__(self):
> return self
>
> def __exit__(self, excType, excValue, excTraceback):
> if excType is None and excValue is None and excTraceback is None:
> self.commit()
> else:
> self.rollback()
>
> This allows the following code:
>
> from __future__ import with_statement
>
> connection = .....
> with connection:
> cursor = connection.cursor()
> cursor.execute("update SomeTable set SomeColumn = "SomeValue")
> cursor.execute("delete from SomeOtherTable where
> SomeOtherColumn = 5)
>
>
> rather than
>
> try:
> cursor = connection.cursor()
> cursor.execute("update SomeTable set SomeColumn = "SomeValue")
> cursor.execute("delete from SomeOtherTable where
> SomeOtherColumn = 5)
> connection.commit()
> except:
> connection.rollback()
>
> I've implemented this in cx_Oracle and it appears to work quite
> nicely. Thoughts?
I've been doing this in Dejavu and it works just fine [1]. Granted, I'm
doing it in a 'sandbox' object (kind of like SQLAlchemy's UnitOfWork),
but the connection object is fine for the DB-API.
However, it's easy to write a context manager wrapper, too. So if the
API doesn't grow this natively (out of scope due to API design
constraints, or maybe implementers just don't want to support it), it
should be easy to do outside of the API.
Robert Brewer
System Architect
Amor Ministries
fumanchu at amor.org
[1] http://projects.amor.org/dejavu/browser/trunk/sandboxes.py#L541
More information about the DB-SIG
mailing list