cr.execute('BEGIN IMMEDIATE') try: rowid = cr.execute('select rowid from element_attribute_values where element=? and attribute=? and value=?', (element, attribute, value)).fetchone()[0] cr.execute('update element_attribute_values set count=count+1 where rowid=?', (rowid,)) except: cr.execute('insert into element_attribute_values values (?, ?, ?, 1)', (element, attribute, value)) cr.execute('COMMIT')
could be replaced by (the below will probably be faster also): cr.execute('BEGIN IMMEDIATE') cr.execute('insert or ignore into element_attribute_values values (?, ?, ?, 0)', (element, attribute, value)) cr.execute('update element_attribute_values set count=count+1 where element=? and attribute=? and value=?', (element, attribute, value)) cr.execute('COMMIT') same caveat that if you want more speed you will have to move your transaction out to cover more updates.