SQLite database not providing error codes when failure to update DB using Python

I copied the following code in python when trying to pick up the python language. When I try updating my SQLite database I do NOT get any error msg when the product code is non-existent or wrong. The success msg is still displayed.The SQLite database (‘test.db’) has a Products table with ProductID, Name, Price as its fields.

Any help provided will be much appreciated.

import sqlite3
conn=sqlite3.connect('test.db')
nm=input('enter name of product: ')
p=int(input('newprice: '))
qry="update Products set price=? where name=?"
cur=conn.cursor()

try:
	cur.execute(qry,(p,nm))
	conn.commit()
	print('Record(s) updated successfully')
except:
	print('Error in update operation')
	conn.rollback()
conn.close

Yes, that’s the way that SQL works. When you do a filtered search, it’s okay for it to not match - or to match more than one (for example, you might say “set price=5 where price=4” to raise the price of every $4 item). In order to know whether there was something to change or not, check the rowcount attribute:

This will tell you how many rows got affected.

By the way, instead of the try/except that you have there (which will absorb all errors and replace them with an opaque message), I strongly recommend that you use a with block:

This will make your debugging far easier, since the exception isn’t getting eaten; and it means less code to write, ergo less bugs.

1 Like