【发布时间】:2021-06-23 03:38:46
【问题描述】:
我正在尝试使用 Python 将 Poke Api website 中的所有 150 个口袋妖怪加载到 SQL 表中。但不幸的是,它将 1 个口袋妖怪加载到 SQL 表中。我需要添加什么才能使其正常工作?我已经尝试了很多东西,我最新的解决方案是 for 循环,但它不起作用..
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()
【问题讨论】: