python - Raise Exception when WHERE doesn't exist during UPDATE query -
i'm using mysqldb / python api project , ran problem:
def activate_acct(act_link): # connect db = mysqldb.connect(host=db_host, user=db_user, passwd=db_pass, db=db_name) # create database cursor cursor = db.cursor() try: sql = """update users set activated = %s activate_code = %s""" cursor.execute(sql, (1, act_link)) db.commit() return "activated" except exception e: return e
the query works, in when activate_code found, activated changed, db updated want, , see success message. problem if activate_code doesn't exist and/or invalid, still success message.
how can have query raise exception if activate_code isn't found where?
an update
statement changes nothing still considered successful. told database make change wherever found value; value found nowhere, change made nowhere. did asked.
if want check make sure change made, can use the .rowcount
attribute of cursor object:
this read-only attribute specifies number of rows last .execute*() produced (for dql statements
select
) or affected (for dml statementsupdate
orinsert
).
after execute update statement, cursor.rowcount > 0
true if , if predicate(s) in where
clause matched. implies update successful.
unrelated specific problem, recommend against using try-except shown in code example. better wrap 1 line , catch errors can handle. if intend calling scope handle error, catch in calling scope (or re-raise in function after doing necessary logging/housekeeping) rather suppressing , returning exception object.
Comments
Post a Comment