[英]Raise Exception when WHERE doesn't exist during UPDATE query
I'm using MySQLdb / Python for an API project and ran into a problem: 我在将MySQLdb / Python用于API项目并遇到问题:
def activate_acct(act_link):
# connect
db = MySQLdb.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASS, db=DB_NAME)
# create a database cursor
cursor = db.cursor()
try:
sql = """UPDATE users
SET activated = %s
WHERE activate_code = %s"""
cursor.execute(sql, (1, act_link))
db.commit()
return "Activated"
except Exception as e:
return 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. 该查询有效,因为找到了activate_code时,激活已更改,dB可以根据需要进行更新,并且看到成功消息。 Problem is that if activate_code doesn't exist and/or is invalid, I still get the success message.
问题是,如果activate_code不存在和/或无效,我仍然会收到成功消息。
How can I have this query raise an exception if activate_code isn't found with WHERE? 如果未在WHERE中找到activate_code,如何使该查询引发异常?
An UPDATE
statement that changes nothing is still considered successful. 不变的
UPDATE
语句仍然被认为是成功的。 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 : 如果要检查以确保已进行更改,则可以使用游标对象的
.rowcount
属性 :
This read-only attribute specifies the number of rows that the last .execute*() produced (for DQL statements like
SELECT
) or affected (for DML statements likeUPDATE
orINSERT
).此只读属性指定最后一个.execute *()产生(对于
SELECT
DQL语句)或受影响的(对于UPDATE
或INSERT
DML语句)受影响的行数。
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. 执行更新语句后,且仅当
WHERE
子句中的谓词匹配时, cursor.rowcount > 0
为true。 This implies your update was successful. 这意味着您的更新成功。
Unrelated to your specific problem, I recommend against using try-except as shown in your code example. 与您的特定问题无关,建议不要使用try-except,如您的代码示例所示。 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.
如果您打算让调用范围处理该错误,则将其捕获在调用范围内(或在执行任何必要的日志记录/内务处理后在函数中重新引发它),而不是抑制该错误并返回异常对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.