我编写了这段代码以删除表中的行–但是,如果输入不在表中的名称,它仍然会输出“数据已成功删除”:
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 :(得分: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
之外。