try pattern for database connection with the close method
Skip Montanaro
skip.montanaro at gmail.com
Sun Feb 22 14:15:09 EST 2015
On Sun, Feb 22, 2015 at 12:41 PM, Mario Figueiredo <marfig at gmail.com> wrote:
> The sqlite context manager doesn't close a database connection on
> exit. It only ensures, commits and rollbacks are performed.
Sorry, I haven't paid careful attention to this thread, so perhaps
this has already been suggested, however... Can't you write your own
class which delegates to the necessary sqlite3 bits and has a context
manager with the desired behavior? Thinking out loud, you could define
a ConnectionMgr class which accepts a sqlite3 connection as a
parameter:
class ConnectionMgr(object):
def __init__(self, conn):
self.conn = conn
def __enter__(self):
...
def __exit__(self, type, value, exception):
if self.conn is not None:
... close self.conn connection here ...
self.conn = None
def __getattr__(self, attr):
return getattr(self.conn, attr)
then...
try:
with MyConnection(lite.connect('data.db')) as db:
...
except lite.DatabaseError:
...
Might also have to __enter__ and __exit__ self.conn as appropriate.
Skip
More information about the Python-list
mailing list