【发布时间】:2017-02-02 21:06:37
【问题描述】:
我有一个 SQLite 数据库,其中包含四个名为餐馆、酒吧、景点和住宿的表。每个表有 3 列,分别命名为 id、name 和 description。我正在尝试使用如下所示的 JSON 文件中的数据填充数据库:
{
"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'])
【问题讨论】:
标签: python sql json python-3.x sqlite