要将JSON数据存入MySQL中,您需要完成以下步骤:
import json
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
cursor = mydb.cursor()
with open('data.json', 'r') as file:
data = json.load(file)
请确保将data.json
替换为您实际的JSON文件路径。
for item in data:
sql = "INSERT INTO yourtable (column1, column2, ...) VALUES (%s, %s, ...)"
values = (item['field1'], item['field2'], ...)
cursor.execute(sql, values)
# 提交更改
mydb.commit()
请将yourtable
替换为您要插入数据的MySQL表名称,并将column1, column2, ...
替换为实际的表列名。
cursor.close()
mydb.close()
下面是一个完整的示例代码:
import json
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
cursor = mydb.cursor()
with open('data.json', 'r') as file:
data = json.load(file)
for item in data:
sql = "INSERT INTO yourtable (column1, column2, ...) VALUES (%s, %s, ...)"
values = (item['field1'], item['field2'], ...)
cursor.execute(sql, values)
mydb.commit()
cursor.close()
mydb.close()
请确保将yourusername
、yourpassword
、yourdatabase
、yourtable
、column1, column2, ...
、field1, field2, ...
替换为实际的数据库连接信息、表名和列名。