вставить несколько строк из объекта JSON в MySQL с Python

0

Я пытаюсь добавить несколько строк из объекта JSON в MySQL, но только последняя строка добавляется в базу данных. Есть ли решение, подобное "для каждой строки"?

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"}]
Теги:
python-3.x
mysql-python

2 ответа

2
Лучший ответ

Ошибка в отступе в курсоре.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()
  • 0
    Это оно! Довольно глупо :-P Спасибо
1

Вы должны поместить INSERT в цикл for:

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"]))

Ещё вопросы

Сообщество Overcoder
Наверх
Меню