0

嗨,当我尝试将数据插入其中时,我创建了一个数据库 wnad,所有内容都添加了接受产品 ID。这是我的代码。

数据库创建,

import sqlite3

def create_table(db_name,table_name,sql):
    with sqlite3.connect(db_name) as db:
        cursor = db.cursor()
        cursor.execute("select name from sqlite_master where name=?",(table_name,))
        result = cursor.fetchall()
        keep_table = True
    if len(result) == 1:
            response = input("The table {0} already exists, do you want to recreate it (y/n)?:  ".format(table_name))
        if response == "y":
            keep_table = False
            print("The table {0} will be recreated - all existing data will be lost.".format(table_name))
            cursor.execute("drop table if exists {0}".format(table_name))
            db.commit()
        else:
            print("The existing table was kept")
    else:
        keep_table = False
    if not keep_table:
        cursor.execute(sql)
        db.commit()

if __name__ == "__main__":
    db_name = "coffee_shop.db"
    sql = """create table Product
             (ProductID intiger,
             Name text,
             Price real,
             primary key(ProductID))"""
create_table(db_name, "Product", sql)

然后我用它来插入数据

import sqlite3

def insert_data(values):
    with sqlite3.connect("coffee_shop.db") as db:
        cursor = db.cursor()
        sql = "insert into Product (Name, Price) values (?,?)"
        cursor.execute(sql,values)
        db.commit()
name = input("what is the product called?:  ")
value = float(input("How much does it cost?:  "))

if __name__ == "__main__":
    product = ("{0}".format(name),"{0}".format(value))
    insert_data(product)

这就是我的数据库最终的样子,没有产品 ID: 数据库屏幕

4

1 回答 1

2

你给了你ProductID的类型intiger;那不是 SQLite 识别的类型。更正它integer,该列将自动递增。

有关更多详细信息,请参阅SQLite 自动增量

于 2013-08-17T16:59:23.613 回答