[英]sqlite3.OperationalError: near “ProductID”: syntax error
我正在嘗試為一家銷售聖誕節用品的商店的庫存管理系統創建數據(是的,我知道聖誕節已經過去了,但這就是任務)。 我的代碼如下:
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級學生,因此您的解決方案和我的問題背后的任何推理都將非常有幫助!)
編輯:表中沒有數據呢。 這將在以后添加。
該異常表明這是一個SQLite語法錯誤。 確實,如果將CREATE TABLE
語句與文檔進行比較,則會發現該語法需要在列定義前后加上括號,例如:
sql = """create table Product
(ProductID integer,
Name text,
Price real,
primary key(ProductID))"""
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.