新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

python读取json数据存入MySQL,python 读取 json

发布时间:2023-09-04 08:02:49

python读取json数据存入MySQL

要将JSON数据存入MySQL中,您需要完成以下步骤:
1. 导入所需的库:
```python
import json
import mysql.connector
```
2. 连接到MySQL数据库:
```python
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
```
3. 创建一个MySQL游标对象:
```python
cursor = mydb.cursor()
```
4. 读取JSON文件:
```python
with open('data.json', 'r') as file:
data = json.load(file)
```
请确保将`data.json`替换为您实际的JSON文件路径。
5. 迭代JSON数据并插入到MySQL表中:
```python
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, ...`替换为实际的表列名。
6. 关闭数据库连接:
```python
cursor.close()
mydb.close()
```
下面是一个完全的示例代码:
```python
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, ...`替换为实际的数据库连接信息、表名和列名。