How do I determine if a Python sqlite UPDATE worked?

Question:

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.

Asked By: tronman

||

Answers:

cursor.rowcount will be 1 if the update was successful (affecting 1 row) or 0 if it failed.

Answered By: Mark Rushakoff

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
Answered By: Kyle Krzeski
command = """Update Table_Name SET col1 = 2 WHERE col2 = 1"""
            dbconn.execute(command)
            sqliteconn.commit()
            if dbconn.rowcount > 0:
                print("Update Statement Executed Successfully")
Answered By: Muhammad Ali
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.