I'm using MySQLdb / Python for an API project and ran into a problem:
db = MySQLdb.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASS, db=DB_NAME)
# create a database cursor
cursor = db.cursor()
sql = """UPDATE users
SET activated = %s
WHERE activate_code = %s"""
cursor.execute(sql, (1, act_link))
except Exception as e:
The query works, in that when activate_code is found, activated is changed, the dB is updated like I want, and I see a success message. Problem is that if activate_code doesn't exist and/or is invalid, I still get the success message.
How can I have this query raise an exception if activate_code isn't found with WHERE?
Best How To :
UPDATE statement that changes nothing is still considered successful. You told the database to make a change wherever it found a certain value; that value was found nowhere, so the change was made nowhere. It did exactly what you asked.
If you want to check to make sure that a change was made, you can use the
.rowcount attribute of a cursor object:
This read-only attribute specifies the number of rows that the last .execute*() produced (for DQL statements like
SELECT ) or affected (for DML statements like
After you execute your update statement,
cursor.rowcount > 0 will be true if and only if the predicate(s) in the
WHERE clause were matched. This implies your update was successful.
Unrelated to your specific problem, I recommend against using try-except as shown in your code example. Better to wrap only one line and catch only errors you can handle. If you intend for the calling scope to handle the error, then catch it in the calling scope (or re-raise it in the function after doing any necessary logging/housekeeping) rather than suppressing it and returning the exception object.