我是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")
该如何解决?任何帮助都会有用的,谢谢
答案 0 :(得分:0)
问题在这里:
"""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)
(如果需要,请使用正确的格式)。