我正在尝试从数据库表中删除记录,而不使用 id 但使用行中的名称



我使用的是SQLite3,

我正在尝试从数据库表中删除一条记录,而不使用id,而是使用一行中的名称。

这是代码:

import sqlite3
def delete_data(product_name):
i_Delete = input(f"You Want To Delete {product_name} ?. (y/n) ")

if i_Delete == 'y':
# Connect to database
connect_to_database = sqlite3.connect('database.db')
# create a cursor
c = connect_to_database.cursor()

# delete record.
c.execute("DELETE from data WHERE produit = product_name")
# commit the command.
connect_to_database.commit()
# close the DB
connect_to_database.close()

elif i_Delete == 'n':
pass
else:
print("Sorry Bad Input. nPlease Verify Your Input")

delete_data('Cheeseburger')

然后我得到这个错误,而不是删除它。

You Want To Delete Cheeseburger ?. (y/n) y
Traceback (most recent call last):
File "deleteDB.py", line 29, in <module>
delete_data('Cheeseburger')
File "deleteDB.py", line 16, in delete_data
c.execute("DELETE from data WHERE produit = product_name")
sqlite3.OperationalError: no such column: product_name

正如我所看到的,问题就在product = product_name

# delete record.
c.execute("DELETE from data WHERE product = product_name")

那我该怎么办,请帮帮我!

在代码中,您使用要查找的变量的名称(而不是其值(。

您需要为execute语句提供一个参数:

c.execute("DELETE from data WHERE produit = ?", [product_name])

请注意,您应该提供一个带有参数的列表,因此是[product_name]而不是product_name

另一种选择是使用字典:

c.execute("DELETE from data WHERE produit = :product_name", {'product_name': product_name})

最新更新