【问题标题】:How can I handle the failure of a DELETE statement to delete any rows?如何处理 DELETE 语句删除任何行的失败?
【发布时间】:2019-03-09 08:09:05
【问题描述】:

我编写这段代码是为了从表中删除一行——但如果我输入一个不在表中的名称,它仍然会输出“数据已成功删除”:

n = input("Enter Student name you want to delete:")
try:
    cur.execute('DELETE FROM studentdata WHERE name=?', (n,))
    print("Data Deleted Successfully")
    conn.commit()
except:
    print("No data found with this name: ")

我该如何正确处理?

【问题讨论】:

  • 删除 0 行并不是您想象的错误。
  • 您可能会找到感兴趣的游标类的rowcount attribute

标签: python database python-3.x sqlite sql-delete


【解决方案1】:

Cursor.execute() 只会在它尝试执行的 SQL 语句失败时引发异常——例如:

>>> cur.execute("This is not SQL")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
sqlite3.OperationalError: near "This": syntax error

>>> cur.execute("SELECT * FROM nonexistent_table;")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
sqlite3.OperationalError: no such table: nonexistent_table

正确不执行任何操作的有效 SQL 语句已成功,未失败,因此不会引发异常。您的DELETE 语句在找不到name 提供的值时什么都不做是正确的,因此没有错误。

您可以使用Cursor.rowcount 属性找出受 SQL 语句影响的行数。重写代码以使用该属性将如下所示:

name = input("Enter Student name you want to delete:")
cur.execute('DELETE FROM studentdata WHERE name = ?;', [name])
if cur.rowcount > 0:
    print("Data Deleted Successfully")
    conn.commit()
else:
    print("No data found with this name:", name)

注意:我将 commit() 留在了您代码中的位置……根据您的应用程序,它可能实际上应该移到 if/else 块之外。

【讨论】:

    猜你喜欢
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 2016-11-01
    • 2019-07-26
    • 2015-05-02
    • 2021-01-01
    相关资源
    最近更新 更多