【问题标题】:Populating SQLite table with JSON data, getting: sqlite3.OperationalError: near "x": syntax error用 JSON 数据填充 SQLite 表,得到:sqlite3.OperationalError: near "x": syntax error
【发布时间】: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


    【解决方案1】:

    您当前的问题是查询中的字符串值周围缺少引号

    您需要正确参数化您的查询让数据库驱动程序担心类型转换、正确放置引号和转义参数:

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

    注意table name cannot be parameterized - 我们必须使用字符串格式将其插入查询 - 确保表名来自您信任的来源或/并正确验证它。

    【讨论】:

    • 感谢您的快速回复。我很确定这是我读到的问题,不幸的是,当我尝试你的方法时,我得到c.execute(query, (detail['id'], detail['name'], detail['description'])) sqlite3.IntegrityError: datatype mismatch
    • @GrantJordan 啊,好吧,如果您在表名之后明确指定列名会发生什么,例如INSERT OR IGNORE INTO {} (COLUMN1, COLUMN2, COLUMN3) VALUES (?, ?, ?)
    • 好的,数据类型不匹配错误是因为我将 id 列设置为 Integer 而不是 Text,并且我的 id 是字母数字。感谢您的帮助,脚本现在可以正常运行!
    猜你喜欢
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多