简体   繁体   中英

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!)

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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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