如何处理DELETE语句未删除行仍提示成功的问题?
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
DELETEstatement, check therowcountattribute of your cursor. This value tells you exactly how many rows were affected by the query. - If
rowcountis greater than 0, it means matching rows were deleted—show the success message and commit the change. - If
rowcountis 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

