try pattern for database connection with the close method

Mario Figueiredo marfig at gmail.com
Fri Feb 20 21:42:20 EST 2015


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.



More information about the Python-list mailing list