在sqlite值中插入变量

时间:2016-12-21 18:04:11

标签: python database sqlite

我写的代码是:

import sqlite3
def insert_product(product):
    with sqlite3.connect("main.db") as db:
        cursor = db.cursor()
        sql=("insert into Products(CatID,Name,Qty,Price)values(?, ?, ?, ?)", (ID,Name,Qty,Price) )
        cursor.execute(sql,product)
        db.commit()

if __name__ == "__main__":
    ID= int(input("enter the CatID of the product:>> "))
    Name = input("Enter the name of the Product you want to inssert: >>")
    Qty = int(input("Enter the quantity of the stock available: >>"))
    Price = int(input("Enter the price of the product: >>"))
    product = (ID,Name,Qty,Price)
    insert_product(product)

我想使用ID,Name,Qty和Price的输入值在数据库中插入值,但它给了我这个错误:

  

文件“C:\ Users \ Admin \ OneDrive \ sql \ insert_product.py”,第6行,在insert_product中       cursor.execute(SQL,产品)   ValueError:操作参数必须为str

1 个答案:

答案 0 :(得分:1)

sql应该是字符串而不是元组,您已经在product中拥有参数:

    sql = "insert into Products (CatID,Name,Qty,Price) values (?, ?, ?, ?)"
    cursor.execute(sql, product)