2016-09-25 86 views
0

我有一個SQLite數據庫,有四個名爲餐廳,酒吧,景點和住宿的表。每個表都有3列,分別命名爲id,名稱和說明。我試圖從一個JSON文件看起來像這樣用數據填充數據庫:使用JSON數據填充SQLite表,得到:sqlite3.OperationalError:接近「x」:語法錯誤

{ 
    "restaurants": [ 
    {"id": "ChIJ8xR18JUn5IgRfwJJByM-quU", "name": "Columbia", "description": "Traditional Spanish restaurant, a branch of a long-standing local chain dating back to 1905."}, 
    ], 
    "bars": [ 
    {"id": "ChIJ8aLBaJYn5IgR60p2CS_RHIw", "name": "Harrys", "description": "Chain outpost serving up Creole dishes in a leafy courtyard or on a balcony overlooking the bay."}, 
    ], 
    "attractions": [ 
    {"id": "ChIJvRwErpUn5IgRaFNPl9Lv0eY", "name": "Flagler", "description": "Flagler College was founded in 1968. Formerly one of Henry Flagler's hotels, the college is allegedly home to many spirits. Tours are offered"}, 
    ], 
    "lodging": [ 
    {"id": "ChIJz8NmD5Yn5IgRfgnWL-djaSM", "name": "Hemingway", "description": "Cottage-style B&B offering a gourmet breakfast & 6 rooms with private baths & traditional decor."}, 
    ] 
} 

每當腳本試圖執行查詢時,我得到sqlite3.OperationalError: near "x": syntax error,其中x是從描述中的一個隨機字。示例錯誤如下所示:sqlite3.OperationalError: near "Spanish": syntax error。這個詞並不總是西班牙文,但它總是一個描述中的一個詞。

我已經嘗試了幾種不同的方法,但總是得到相同的結果,這裏是一個方法我都試過:

import sqlite3 
import json 

places = json.load(open('locations.json')) 
db = sqlite3.connect('data.db') 

for place, data in places.items(): 
    table = place 
    for detail in data: 
     query = 'INSERT OR IGNORE INTO ' + place + ' VALUES (?, ?, ?), (' \ 
       + detail['id'] + ',' + detail['name'] + ',' + detail['description'] + ')' 
     c = db.cursor() 
     c.execute(query) 
     c.close() 

而且我也嘗試寫這樣的查詢:

query = 'INSERT OR IGNORE INTO {} VALUES ({}, {}, {})'\ 
      .format(table, detail['id'], detail['name'], detail['description']) 

回答

3

您目前的問題是周圍查詢中的字符串值缺少引號

你需要正確參數查詢讓有關類型轉換的數據庫驅動程序的擔心,把報價適當和逃避的參數:

query = """ 
    INSERT OR IGNORE INTO 
     {} 
    VALUES 
     (?, ?, ?)""".format(table) 

c.execute(query, (detail['id'], detail['name'], detail['description'])) 

注意,table name cannot be parameterized - 我們必須使用字符串格式化來將其插入到查詢中 - 確保表名來自您信任的來源或/並正確驗證它。

+0

感謝您的快速響應。我很確定這是我讀過的問題,不幸的是,當我嘗試你的方法時,我得到了'c.execute(query,(detail ['id'],detail ['name'],detail ['description']] ))sqlite3.IntegrityError:datatype mismatch' –

+0

@GrantJordan啊,好吧,如果你在表名後面明確指定了列名,會發生什麼,例如'INSERT或IGNORE INTO {}(COLUMN1,COLUMN2,COLUMN3)VALUES(?,?,?)' – alecxe

+0

好吧,數據類型不匹配錯誤是因爲我將id列設置爲Integer而不是Text,而我的id是字母數字。感謝您的幫助,腳本現在運行無誤! –

相關問題