我使用JSON解析的數據填充數據庫。當我執行我的INSERT
聲明時,出現錯誤:sqlite3.OperationalError: no such column: None
。一些JSON數據返回null
,這會導致Python將None
插入表中,但我相信這應該沒問題?有誰知道問題是什麼?當在Python中插入sqlite 3時出現OperationalError
回溯: Traceback (most recent call last): File "productInfoScraper.py", line 71, in <module> ")")
我INSERT
聲明在Python:
cursor.execute("INSERT INTO ProductInfo VALUES(" +
str(data["data"]["product_id"]) + ", " +
"'" + str(data["data"]["product_name"]) + "'" + ", " +
"'" + str(data["data"]["ingredients"]) + "'" + ", " +
"'" + str(data["data"]["serving_size"]) + "'" + ", " +
str(data["data"]["calories"]) + ", " +
str(data["data"]["total_fat_g"]) + ", " +
str(data["data"]["total_fat_percent"]) + ", " +
str(data["data"]["fat_saturated_g"]) + ", " +
str(data["data"]["fat_saturated_percent"]) + ", " +
str(data["data"]["fat_trans_g"]) + ", " +
str(data["data"]["fat_trans_percent"]) + ", " +
str(data["data"]["cholesterol_mg"]) + ", " +
str(data["data"]["sodium_mg"]) + ", " +
str(data["data"]["sodium_percent"]) + ", " +
str(data["data"]["carbo_g"]) + ", " +
str(data["data"]["carbo_percent"]) + ", " +
str(data["data"]["carbo_fibre_g"]) + ", " +
str(data["data"]["carbo_fibre_percent"]) + ", " +
str(data["data"]["carbo_sugars_g"]) + ", " +
str(data["data"]["protein_g"]) + ", " +
str(data["data"]["vitamin_a_percent"]) + ", " +
str(data["data"]["vitamin_c_percent"]) + ", " +
str(data["data"]["calcium_percent"]) + ", " +
str(data["data"]["iron_percent"]) + ", " +
"'" + str(data["data"]["micro_nutrients"]) + "'" + ", " +
"'" + str(data["data"]["tips"]) + "'" + ", " +
str(data["data"]["diet_id"]) + ", " +
"'" + str(data["data"]["diet_type"]) + "'" +
")")
我CREATE TABLE
聲明:
cursor.execute("CREATE TABLE ProductInfo(product_id INT, product_name TEXT,\
ingredients TEXT, serving_size TEXT, calories INT, total_fat_g INT,\
total_fat_percent INT, fat_saturated_g INT, fat_saturated_percent INT,\
fat_trans_g INT, fat_trans_percent INT, cholesterol_mg INT, sodium_mg\
INT, sodium_percent INT, carbo_g INT, carbo_percent INT, carbo_fibre_g\
INT, carbo_fibre_percent INT, carbo_sugars_g INT, protein_g INT,\
vitamin_a_percent INT, vitamin_c_percent INT, calcium_percent INT,\
iron_percent INT, micro_nutrients TEXT, tips TEXT, diet_id INT, diet_type\
TEXT)")
[以這種方式構建插入語句是一個非常糟糕的主意](http://xkcd.com/327/)。除了該漫畫中演示的安全/安全問題之外,還很難使所有引用都正確,並且很難調試簡單的拼寫錯誤。 – abarnert
@abanert我會如何正確地做到這一點? 類似於'cursor.execute(「INSERT INTO表VALUES(?,'?')」,a,b)'或者其他什麼東西? –
那麼,你不要在佔位符周圍引用引號 - 整個問題的一部分是數據庫爲你引用引用。而且,指定的佔位符在這裏比位置更易讀。詳情請參閱我的回答。 (另外,作爲一個方面說明,通常使用不帶列列表的INSERT來依賴列的順序通常被認爲是一個壞主意,但我認爲這不是你的問題。) – abarnert