我有一个 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'])
最佳答案
您当前的问题是查询中字符串值周围缺少引号。
您需要正确地参数化您的查询让数据库驱动程序担心类型转换、正确放置引号和转义参数:
query = """
INSERT OR IGNORE INTO
{}
VALUES
(?, ?, ?)""".format(table)
c.execute(query, (detail['id'], detail['name'], detail['description']))
请注意 table name cannot be parameterized - 我们必须使用字符串格式将其插入到查询中 - 确保表名来自您信任的来源或/并正确验证它。
关于python - 使用 JSON 数据填充 SQLite 表,得到 : sqlite3. OperationalError: near "x": syntax error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39687292/