久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

python讀取json數據存入MySQL

175次閱讀
沒有評論

共計 1134 個字符,預計需要花費 3 分鐘才能閱讀完成。

要將 JSON 數據存入 MySQL 中,您需要完成以下步驟:

  1. 導入所需的庫:
import json
import mysql.connector
  1. 連接到MySQL 數據庫
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
  1. 創建一個 MySQL 游標對象:
cursor = mydb.cursor()
  1. 讀取 JSON 文件:
with open('data.json', 'r') as file:
data = json.load(file)

請確保將 data.json 替換為您實際的 JSON 文件路徑。

  1. 迭代 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, ... 替換為實際的表列名。

  1. 關閉 數據庫 連接:
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、yourdatabaseyourtable、column1, column2, ...field1, field2, ... 替換為實際的數據庫連接信息、表名和列名。

丸趣 TV 網 – 提供最優質的資源集合!

正文完
 
丸趣
版權聲明:本站原創文章,由 丸趣 2023-12-22發表,共計1134字。
轉載說明:除特殊說明外本站除技術相關以外文章皆由網絡搜集發布,轉載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 金乡县| 高淳县| 黄冈市| 新余市| 梓潼县| 神木县| 修武县| 余江县| 新野县| 云梦县| 新闻| 林西县| 历史| 嵩明县| 四会市| 海伦市| 新和县| 江阴市| 安顺市| 新晃| 昌邑市| 阿克苏市| 明光市| 尉氏县| 乐至县| 北川| 汉阴县| 成安县| 张家川| 格尔木市| 邯郸市| 新营市| 甘泉县| 贵阳市| 邵阳县| 津市市| 阜平县| 平南县| 阿拉善右旗| 长垣县| 台东市|