Search code examples
pythonsqlpython-3.xsqlitesql-delete

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


I'm using SQLite3,

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

Here is the CODE:

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')

Then i get this error instead of delete it.

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

As i can see the problem is here on product = product_name

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

So What can i do, Please Help !


Solution

  • In your code you use the name of the variable (instead of its value) to be looked for.

    You need to provide a parameter to the execute statement:

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

    Please note, that you are supposed to provide a list with parameters, therefore [product_name] instead of product_name.

    Another option is to use a dictionary:

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