下达“订单”后如何更新库存水平?

时间:2018-12-27 02:39:49

标签: python database sqlite

我正在尝试在带sqlite3的python中使用数据库。我正在为商店创建库存管理系统,并且有一个产品表,其中包含以下字段:ProductID,名称,StockLevel。

购买时,我正在努力更新库存水平。因此,应从订购的数量中减去特定产品的库存水平。

我的代码:

def update_stock(product,no_bought):
    with sqlite3.connect("shop.db") as db:
        cursor = db.cursor()
        sql = "UPDATE Product SET StockLevel = StockLevel - %s WHERE Name = %s" 
        cursor.execute(sql, (no_bought, product))
        db.commit()

product = input("What product has been bought: ")
no_bought = input("How much has been bought: ")
update_stock(product,no_bought)
  

sqlite3.OperationalError:“%”附近:语法错误

为什么会出现此错误?

2 个答案:

答案 0 :(得分:2)

您需要为两个变量使用两个占位符,并正确地参数化查询(请注意SQL injections!)

sql = """
    UPDATE  
        Product 
    SET 
        StockLevel = StockLevel - ?
    WHERE 
        Name = ?
"""
cursor.execute(sql, (no_bought, product))

请注意如何将查询参数分别传递到execute(),以及查询本身如何有2个占位符。

答案 1 :(得分:1)

根据sqlite3的文档,将?用作占位符。

def update_stock(product, no_bought):
    with sqlite3.connect("shop.db") as db:
        cursor = db.cursor()
        sql = "UPDATE Product SET StockLevel = StockLevel - ? WHERE Name = ?"
        cursor.execute(sql, (no_bought, product))
        db.commit()
product = input("What product has been bought: ")
no_bought = input("How much has been bought: ")
update_stock(product,no_bought)