简体   繁体   English

在UPDATE查询期间不存在WHERE时引发异常

[英]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 like UPDATE or INSERT ). 此只读属性指定最后一个.execute *()产生(对于SELECT DQL语句)或受影响的(对于UPDATEINSERT 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.

相关问题 为什么在迭代期间修改dict并不总是引发异常? - Why modifying dict during iteration doesn't always raise exception? 在前两列不存在的python中更新函数 - Update a function in python where first two columns doesn't exist 为什么getattr()在属性不存在时抛出异常? - Why is getattr() throwing an exception when an attribute doesn't exist? 当 cp 没有时,为什么 shutil.copy() 会引发权限异常? - Why would shutil.copy() raise a permission exception when cp doesn't? Django:当用户根本不填写表单时如何引发异常? - Django: How to raise an exception when a user doesn't fill in a form at all? ShopifyQL 引发错误“类型‘QueryRoot’上不存在字段‘shopifyqlQuery’” - ShopifyQL raise error "Field 'shopifyqlQuery' doesn't exist on type 'QueryRoot'" 行不存在时的Django select_for_update - Django select_for_update when row doesn't exist yet 为什么当你设置一个不存在的类的属性时,python 不会抛出异常 - Why doesn't python throw an exception when you set an attribute of a class that doesn't exist 使用类方法实现抽象类不会引发异常 - Implementing an abstract class with a class method doesn't raise an exception 引发*错误在Python 2.7中不起作用; 如何提出先前捕获的异常? - raise *error doesn't work in Python 2.7; how can I raise a previously captured exception?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM