gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:27:15 24 4
gpt4 key购买 nike

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

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

我该如何正确处理这个问题?

最佳答案

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 block 。

关于python - 如何处理 DELETE 语句删除任何行的失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55075297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com