【问题标题】:Python Json TypeError: not all arguments converted during string formattingPython Json TypeError:字符串格式化期间并非所有参数都转换
【发布时间】:2020-11-11 13:57:47
【问题描述】:

我是 json 的新手。我在我的 python 项目中使用 mysql 和 json。我有这样的json文件:

我想将一些内容存储到 sql 数据库,但是当我运行代码时出现错误TypeError: not all arguments converted during string formatting。这是一段代码:

def create_db(db_name, table_name):
    # try:
    db = dbconnect()
    cursor = db.cursor()

    cursor.execute("SET sql_notes = 0;")

    cursor.execute("CREATE DATABASE IF NOT EXISTS {}".format(db_name))

    cursor.execute("SET sql_notes = 0;")

    cursor.execute(
        """CREATE TABLE IF NOT EXISTS {}.{}(waktu varchar(150),plate varchar(20),region varchar(150), score varchar(20), filename varchar(50));""".format(db_name, table_name))

    cursor.execute("SET sql_notes = 1;")

    with open('data.json') as f:
        data = json.load(f)

    for i in data:
        cursor.execute(
            """INSERT INTO {}.{}(waktu, plate, region, score, filename) VALUES(%s,%s)""".format
            (db_name, table_name),
            (i['timestamp'], i['results'][0]['plate'], i['results'][0]['region']['code'], i['results'][0]['score'], i['filename']))

    db.commit()
    db.close()

    # except Exception as e:
    #     print(e)

create_db(db_name="plate_recognizer", table_name="kendaraan")

如何解决这个问题?任何帮助将是appriciate,谢谢

【问题讨论】:

    标签: python mysql json database


    【解决方案1】:

    问题出在这里:

     """INSERT INTO {}.{}(waktu, plate, region, score, filename) VALUES(%s,%s)""".format
                (db_name, table_name),
                (i['timestamp'], i['results'][0]['plate'], i['results'][0]['region']['code'], i['results'][0]['score'], i['filename']))
    
    

    您提供了 5 个参数((i['timestamp'], i['results'][0]['plate'], i['results'][0]['region']['code'], i['results'][0]['score'], i['filename']))),但只有 2 种格式(VALUES(%s,%s))。您应该添加更多这样的格式:VALUES(%s, %s, %s, %s, %s)(如果需要,请使用正确的格式)。

    【讨论】:

      猜你喜欢
      • 2015-10-28
      • 2013-10-21
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      相关资源
      最近更新 更多