简体   繁体   中英

How do I add multiple items with a for loop in Python to a SQL table?

I'm trying to load all the 150 pokemons from the Poke Api website in a SQL table with Python. But unfortunately it loads 1 pokemon to the SQL-table. What do I need to add to make it work? I've tried a lot of things already, my latest solution is a for loop, but it doesn't work..

import mysql.connector
import json
import requests

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="",
  database="pokemon",
)
cursor = mydb.cursor()

for i in range(1,150):
    url = 'https://pokeapi.co/api/v2/pokemon/'+ str(i)
    r = requests.get(url)
    pokemontable = json.loads(r.text)

pokemonlist = []
for i in pokemontable:
  pokemon = {
  'id': pokemontabel['id'],
  'name': pokemontabel['name'],
  'weight': pokemontabel['weight'],
  'height': pokemontabel['height']
  }

pokemonlist.append(pokemon)

cursor.execute("CREATE TABLE pokemon (id INT(22), name VARCHAR(255), weight INT(22), height INT(22))")

sql = sql = "INSERT INTO pokemon " \
      "(id, name, weight, height) " \
      "VALUES (%(id)s, %(name)s, %(weight)s, %(height)s)"

cursor.execute(sql, pokemon)
print('Yes, I have catch'em all!')

mydb.commit()
mydb.close()

pokemonlist.append(pokemon) should intended to be part of the loop, also you don't need to assign it to variable just do:

pokemonlist.append({
  'id': pokemontabel['id'],
  'name': pokemontabel['name'],
  'weight': pokemontabel['weight'],
  'height': pokemontabel['height']
})

(or use a list comprehension and build that list when you need it in the query).

The sql = sql is probably a typo.

You have two options:

  1. either loop over your execute for each pokemon:
for p in pokemonlist:
   cursor.execute(sql, p)
  1. Or create a dynamic sql statement where the values part '(%(id)s, %(name)s, %(weight)s, %(height)s)' is repeated len(pokemonlist) times separated by comma and pass in the pokemonlist to the execute:
sql = 'INSERT INTO pokemon(id, name, weight, height) VALUES ' + ','.join(['(%(id)s, %(name)s, %(weight)s, %(height)s)'] * len(pokemonlist))
cursor.execute(sql, pokemonlist)

I haven't test this, btw, you might need to use positional rather than named parameters. If you try it, let me know how it goes.

pokemonlist.append(pokemon) line should be indented. Also you should use this:

sql = """INSERT INTO pokemon 
(id, name, weight, height) 
VALUES (%(id)s, %(name)s, %(weight)s, %(height)s)"""
for pokemon in pokemonlist:
    cursor.execute(sql, pokemon)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM