社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

使用python删除数据库表中的行

Chandio • 5 年前 • 1273 次点击  

我编写此代码是为了从表中删除行,但如果输入的名称不在表中,它仍然输出“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社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55014
 
1273 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Zero Piraeus
Reply   •   1 楼
Zero Piraeus    6 年前

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 属性。重新编写代码以使用属性如下:

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