2016-12-28 115 views
0

我试图为一家销售圣诞用品的店铺创建一个库存管理系统的数据(是的,我知道圣诞节已经过去了,但那是任务)。我的代码如下:sqlite3.OperationalError:在“ProductID”附近:语法错误

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级学生,所以任何推理和解决方案背后的问题都是非常有帮助的!)

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

回答

0

该异常提示它是SQLite语法错误。事实上,如果你对documentation比较你CREATE TABLE声明,你会发现语法要求各地列定义括号,如:

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

所以基本!我应该更清楚地知道。 –

相关问题