I'm using sqlite3 in Python. I want to know if my UPDATE statement worked or not without doing another database query:
c.execute('update students set gpa=3.5 where stuid=123')
If there isn't a student with stuid 123 then obviously the update fails.
Introduction to SQLite UPDATE statement First, specify the table where you want to update after the UPDATE clause. Second, set new value for each column of the table in the SET clause. Third, specify rows to update using a condition in the WHERE clause. The WHERE clause is optional.
cursor.rowcount
will be 1 if the update was successful (affecting 1 row) or 0 if it failed.
For a slightly more complete answer for if you want to handle error and success:
c.execute('update students set gpa=3.5 where stuid=123')
if c.rowcount < 1:
#error
else:
#success
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With