try pattern for database connection with the close method
Peter Otten
__peter__ at web.de
Sat Feb 21 10:27:17 EST 2015
Ian Kelly wrote:
> On Sat, Feb 21, 2015 at 5:22 AM, Mark Lawrence <breamoreboy at yahoo.co.uk>
> wrote:
>> On 21/02/2015 02:42, Mario Figueiredo wrote:
>>>
>>> Hello all,
>>>
>>> I'm using the following pattern for db access that requires me to
>>> close the connection as soon as it is not needed:
>>>
>>> import sqlite3 as lite
>>>
>>> try:
>>> db = lite.connect('data.db')
>>> except lite.DatabaseError:
>>> raise OSError('database file corrupt or not found.')
>>> else:
>>> try:
>>> with db:
>>> db.execute(sql, parms)
>>> except lite.IntegrityError:
>>> raise ValueError('invalid data')
>>> finally:
>>> db.close()
>>>
>>> Since it's a bit verbose, is there a better way?
>>>
>>> Note: The user of this API has the whole database functionality
>>> abstracted away. Hence the exception channeling in the except clauses.
>>>
>>
>> Use your context manager at the outer level.
>>
>> import sqlite3 as lite
>>
>> try:
>> with lite.connect('data.db') as db:
>> try:
>> db.execute(sql, parms)
>> except lite.IntegrityError:
>> raise ValueError('invalid data')
>> except lite.DatabaseError:
>> raise OSError('database file corrupt or not found.')
>
> This could result in the OSError being misleadingly raised due to some
> DatabaseError raised by the execute rather than the connect.
The OP probably wants to catch these DatabaseErrors, too. Also, the chance
of a misleading traceback has been greatly reduced with the advent of
chained exceptions.
More information about the Python-list
mailing list