如何处理DELETE语句删除任何行的失败?

问题描述 投票:1回答:1

我写了这段代码来删除表中的一行 - 但是如果我输入的名称不在表中,它仍会输出“Data Deleted Successfully”:

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: ")

我该如何妥善处理?

python database python-3.x sqlite sql-delete
1个回答
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块之外。

© www.soinside.com 2019 - 2024. All rights reserved.