You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理DELETE语句未删除行仍提示成功的问题?

Fixing the Misleading "Success" Message When Deleting Non-Existing Rows

Hey there! The issue with your current code is that running a DELETE query doesn’t throw an error when no rows match your WHERE clause—it simply affects zero rows. Since there’s no actual database failure happening, your except block never triggers, leading to that confusing success message even when the name doesn’t exist in the table.

Here’s how to handle this correctly:

  • After executing the DELETE statement, check the rowcount attribute of your cursor. This value tells you exactly how many rows were affected by the query.
  • If rowcount is greater than 0, it means matching rows were deleted—show the success message and commit the change.
  • If rowcount is 0, no matching records were found, so you should inform the user about that instead.

Modified Code Example:

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

Why This Works:

Database operations like DELETE only raise exceptions when there’s a critical failure (like invalid SQL syntax, lost connection, or permission issues). Deleting zero rows is a valid, expected outcome—not an error—so relying on exceptions here isn’t the right approach. Checking rowcount directly gives you the precise feedback you need to handle both scenarios properly.

内容的提问来源于stack exchange,提问作者K_Chandio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:28:08