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

时间:2016-12-28 11:02:30

标签: python-3.x sqlite

我正在尝试为一家销售圣诞用品的商店创建一个库存管理系统的数据(是的,我知道圣诞节已经过去,但这就是任务)。我的代码如下:

import sqlite3

def existing_table(table_name,sql):
    response = input("The table {0} already exists. Do you wish to recreate it? (Y/N)")
    if response.upper() == "Y":
        keep_table = False
        print("The {0} table will be recreated. All existing data will be erased.".format(table_name))
        cursor.execute("drop table if exists {0}".format(table_name))
        db.commit()
    elif response.upper() == "N":
        print("The existing table was kept.")
    else:
        existing_table(table_name,sql)
    if not keep_table:
        cursor.execute(sql)
        db.commit()

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:
            existing_table()
        cursor.execute(sql)
        db.commit()

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

但是,当我运行它时,我收到此错误消息:

Traceback (most recent call last):
line 36, in <module>
    create_table(db_name,"Product",sql)
line 26, in create_table
    cursor.execute(sql)
sqlite3.OperationalError: near "ProductID": syntax error

这里有什么问题,如何解决? (请记住,我是一年级的A级学生,所以你的解决方案背后的任何理由都非常有用!)

编辑:表格中还没有数据。这将在稍后添加。

1 个答案:

答案 0 :(得分:0)

该异常暗示它是SQLite语法错误。实际上,如果您将setTimeout语句与documentation进行比较,您会发现语法需要围绕列定义括起来,例如:

console.log("a");
setTimeout(function(){
    console.log("b");
}, 5000);
console.log("c");