try pattern for database connection with the close method

Peter Otten __peter__ at web.de
Sat Feb 21 12:02:50 EST 2015


Ian Kelly wrote:

> On Sat, Feb 21, 2015 at 8:27 AM, Peter Otten <__peter__ at web.de> wrote:
>> Ian Kelly wrote:
>>
>>> On Sat, Feb 21, 2015 at 5:22 AM, Mark Lawrence <breamoreboy at yahoo.co.uk>
>>> wrote:
>>>> 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.
>>
> 
> Yes, but the point is that OSError is probably inappropriate in that case.

Perhaps, but the example I gave in my other post:

>>> with open("data.db", "wb") as f:
...     f.write(os.urandom(1024)) # put random bytes into data.db

>>> db = sqlite3.connect("data.db")
>>> db.execute("create table foo (bar, baz);")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
sqlite3.DatabaseError: file is encrypted or is not a database

matches the "database file corrupt" part of the error message provided by 
the OP.




More information about the Python-list mailing list