try pattern for database connection with the close method

Mark Lawrence breamoreboy at yahoo.co.uk
Sat Feb 21 07:22:58 EST 2015


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.')

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list