python读取json数据存入MySQL


要将JSON数据存入MySQL中,您需要完成以下步骤:

    导入所需的库:
import jsonimport mysql.connector
    连接到MySQL数据库:
mydb = mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",database="yourdatabase")
    创建一个MySQL游标对象:
cursor = mydb.cursor()
    读取JSON文件:
with open('data.json', 'r') as file:data = json.load(file)

请确保将data.json替换为您实际的JSON文件路径。

    迭代JSON数据并插入到MySQL表中:
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 jsonimport mysql.connectormydb = 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()

请确保将yourusernameyourpasswordyourdatabaseyourtablecolumn1, column2, ...field1, field2, ...替换为实际的数据库连接信息、表名和列名。


上一篇:sql中unique和distinct

下一篇:sql server数据库中raiserror函数的用法


python
Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器