-2

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 !

sophros
  • 14,672
  • 11
  • 46
  • 75
  • 1
    You’re missing quotes, if `product_name` is supposed to be a text literal, and not a column name. – CBroe Dec 15 '20 at 10:53
  • 1
    _“without using id but using a name”_ - why? That appears to make rather little sense to begin with. – CBroe Dec 15 '20 at 10:54

1 Answers1

2

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})
sophros
  • 14,672
  • 11
  • 46
  • 75
  • Now the error turn to this: File "deleteDB.py", line 16, in delete_data c.execute("DELETE from data WHERE produit = %", [product_name]) sqlite3.OperationalError: near "%": syntax error – Thierry Mugisha Dec 15 '20 at 11:51
  • 1
    @red_ant: corrected. It seems that Python API supports `?` instead of `%` as [this questions' answers suggest](https://stackoverflow.com/questions/38925115/sqlite3-operationalerror-near-syntax-error) – sophros Dec 15 '20 at 12:00
  • Thanks, I use ? instead of % now it works Thanks. – Thierry Mugisha Dec 15 '20 at 12:03