要將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, ...
替換為實際的數據庫連接信息、表名和列名。