简体   繁体   English

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

[英]sqlite3.OperationalError: near “ProductID”: syntax error

I'm trying to create a data for a stock management system for a shop selling Christmas items (yes, I know Christmas has gone, but that's the task). 我正在尝试为一家销售圣诞节用品的商店的库存管理系统创建数据(是的,我知道圣诞节已经过去了,但这就是任务)。 My code is as below: 我的代码如下:

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)

However, when I run it, I get this error message: 但是,当我运行它时,出现以下错误消息:

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

What's wrong here, and how can this be solved? 这是怎么回事,如何解决? (Bear in mind I'm a first year A-level student, so any reasoning behind your solution and my problem is extremely helpful!) (请记住,我是一年级的A级学生,因此您的解决方案和我的问题背后的任何推理都将非常有帮助!)

EDIT: There is no data in the table yet. 编辑:表中没有数据呢。 This will be added later on. 这将在以后添加。

The exception hints that it's an SQLite syntax error. 该异常表明这是一个SQLite语法错误。 Indeed, if you compare your CREATE TABLE statement against the documentation , you'll find that the syntax requires parentheses around the column definitions, such as: 确实,如果将CREATE TABLE语句与文档进行比较,则会发现该语法需要在列定义前后加上括号,例如:

sql = """create table Product
        (ProductID integer,
        Name text,
        Price real,
        primary key(ProductID))"""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM