[英]How to update stock level after 'order' has been made?
我正在使用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:接近“%”:語法錯誤
為什么會出現此錯誤?
您需要為兩個變量使用兩個占位符,並正確設置查詢參數 (請注意SQL注入 !):
sql = """
UPDATE
Product
SET
StockLevel = StockLevel - ?
WHERE
Name = ?
"""
cursor.execute(sql, (no_bought, product))
注意如何將查詢參數分別傳遞給execute()
,以及查詢本身如何有2個占位符。
使用?
根據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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.