sqlite3 with context manager

Tim Arnold Tim.Arnold at sas.com
Tue Sep 6 13:18:07 EDT 2011


On 9/3/2011 3:03 AM, Carl Banks wrote:
> On Friday, September 2, 2011 11:43:53 AM UTC-7, Tim Arnold wrote:
>> Hi,
>> I'm using the 'with' context manager for a sqlite3 connection:
>>
>> with sqlite3.connect(my.database,timeout=10) as conn:
>>               conn.execute('update config_build set datetime=?,result=?
>> where id=?',
>>                                 (datetime.datetime.now(), success,
>> self.b['id']))
>>
>> my question is what happens if the update fails? Shouldn't it throw an
>> exception?
>
> If you look at the sqlite3 syntax documentation, you'll see it has a SQL extension that allows you to specify error semantics.  It looks something like this:
>
> UPDATE OR IGNORE
> UPDATE OR FAIL
> UPDATE OR ROLLBACK
>
> I'm not sure exactly how this interacts with pysqlite3, but using one of these might help it throw exceptions when you want it to.
>
>
> Carl Banks

I see now. You can use 'update or fail' if you have the extensions built 
in: http://docs.python.org/library/sqlite3.html#f1

example of use, line 76:
http://projects.developer.nokia.com/TECwidget/browser/data/montreal/updsqlite.py?rev=7ca2ebd301ed1eff0e2c28283470db060b872cd6

For my case, however, I'll follow Ian's advice and check on the rowcount 
after the update.

thanks for the explanation and advice,
--Tim



More information about the Python-list mailing list