我有一个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'])
感谢您的快速响应。我很确定这是我读过的问题,不幸的是,当我尝试你的方法时,我得到了'c.execute(query,(detail ['id'],detail ['name'],detail ['description']] ))sqlite3.IntegrityError:datatype mismatch' –
@GrantJordan啊,好吧,如果你在表名后面明确指定了列名,会发生什么,例如'INSERT或IGNORE INTO {}(COLUMN1,COLUMN2,COLUMN3)VALUES(?,?,?)' – alecxe
好吧,数据类型不匹配错误是因为我将id列设置为Integer而不是Text,而我的id是字母数字。感谢您的帮助,脚本现在运行无误! –