我正在尝试从我的数据库 table 中删除一条记录,但不使用 id,而是使用连续的名称

I'm trying to delete a record from my database table without using id but using a name that is in a row

我正在使用 SQLite3,

我正在尝试从我的数据库 table 中删除一条记录,但没有使用 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})