try pattern for database connection with the close method

Ian Kelly ian.g.kelly at gmail.com
Sat Feb 21 10:16:28 EST 2015


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.



More information about the Python-list mailing list