python - 使用 Python 在 MySQL 中从 JSON 对象插入多行

标签 python mysql python-3.x mysql-python

我正在尝试将 JSON 对象中的多行添加到 MySQL,但只有最后一行被添加到数据库中。有没有像“for each row”这样的解决方案?

import requests
import json
import pymysql
import urllib.request

con = pymysql.connect(host = 'host', port = 3306, user = 'user', passwd = 'pass', db = 'db')
cursor = con.cursor()
url = 'url to json'
urllib.request.urlopen(url).read()
response = urllib.request.urlopen(url).read()
json_obj = str(response, 'utf-8')
json_obj = json.loads(response.decode('utf-8'))

for obj in json_obj:
    print(obj["one"])
    print(obj["two"])
    print(obj["three"])
    print(obj["four"])
    print(obj["five"])
    print(obj["six"])
    print(obj["seven"])

cursor.execute("INSERT INTO test (one, two, three, four, five, six, seven) VALUES (%s,%s,%s,%s,%s,%s,%s)", (obj["one"], obj["two"], obj["three"], obj["four"], obj["five"], obj["six"], obj["seven"]))

con.commit()
con.close()

JSON 对象如下所示,一次可以保存 5 到 50 条记录

[{"one":"1.232.123","two":"test","three":1242,"four":"2,4","five":"test","six":"test","seven":"test"},{"one":"3.322.876","two":"test","three":1312,"four":"3,4","five":"test","six":"test","seven":"test"},{"one":"1.232.123","two":"test","three":1242,"four":"2,4","five":"test","six":"test","seven":"test"},{"one":"3.322.876","two":"test","three":1312,"four":"3,4","five":"test","six":"test","seven":"test"}]

最佳答案

cursor.execute 中的缩进错误。 这是固定代码

import requests
import json
import pymysql
import urllib.request

con = pymysql.connect(host = 'host', port = 3306, user = 'user', passwd = 'pass', db = 'db')
cursor = con.cursor()
url = 'url to json'
urllib.request.urlopen(url).read()
response = urllib.request.urlopen(url).read()
json_obj = str(response, 'utf-8')
json_obj = json.loads(response.decode('utf-8'))

for obj in json_obj:
    print(obj["one"])
    print(obj["two"])
    print(obj["three"])
    print(obj["four"])
    print(obj["five"])
    print(obj["six"])
    print(obj["seven"])

    cursor.execute("INSERT INTO test (one, two, three, four, five, six, seven) VALUES (%s,%s,%s,%s,%s,%s,%s)", (obj["one"], obj["two"], obj["three"], obj["four"], obj["five"], obj["six"], obj["seven"]))

con.commit()
con.close()

关于python - 使用 Python 在 MySQL 中从 JSON 对象插入多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52443239/

相关文章:

python - 运行时错误 : PyTorch does not currently provide packages for PyPI

MySQL:仅显示三月内的日期

mysql - 选择显示第一个唯一值的行

php - 捕获所有 MySQL 错误的函数?

python - Dlib 裁剪后的图像是蓝色的

python - 从维基百科页面的类别中获取更一般的类别

python - 尝试从网页监控产品,但未按预期工作

python-3.x - 如何在 pandas.read_csv() 之前预处理数据

python - 如何在另一个已保存的文件上显示图形? (Python)

python - Seaborn Catplot : Number of rows must be a positive integer, 不是 0