how i can make this delete query sqlite3 work in my python project?

60 Views Asked by At

basically this is the syntax of deleting in sqlite3, how can i make it work in this def (function)?? for instance when i enter 2 i want to delete id number 1

import sqlite3

connection = sqlite3.connect("store.db")
cur = connection.cursor()

try:
    cur.execute("CREATE TABLE store(id int, name var(250), price int,   manufacturer_country var(250));")

except Exception as e:
    print('table creation failed')

def delete_a_product(): 
    global cur
    global connection
    
    id = int(input("enter product id: "))    
    
    query = 'DELETE FROM store WHERE id=?'
    cur.execute(query)  
    connection.commit()  
    
    global products
    product_index = int(input('enter a product_index: ')) 
    lower_bound = 1
    upper_bound = len(products) 
    if product_index >= lower_bound and product_index <= upper_bound:
        del products[product_index-1] 
    else:
        print("Enter a valid price")
1

There are 1 best solutions below

0
On

This is closer to what you were after. This code still won't work as is, of course, because the table won't contain any products immediately after you have created it.

import sqlite3

connection = sqlite3.connect("store.db")
cur = connection.cursor()

cur.execute("CREATE TABLE IF NOT EXISTS store(id int, name var(250), price int, manufacturer_country var(250));")

def delete_a_product(product): 
    query = 'DELETE FROM store WHERE id=?'
    cur.execute(query, (product,))
    connection.commit()
    
product_index = int(input('enter a product_index to delete: ')) 
delete_a_product(product_index-1)