[英]How do I add multiple items with a for loop in Python to a SQL table?
我正在尝试使用 Python 将Poke Api 网站中的所有 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()
pokemonlist.append(pokemon)
应该是循环的一部分,你也不需要将它分配给变量,只需执行以下操作:
pokemonlist.append({
'id': pokemontabel['id'],
'name': pokemontabel['name'],
'weight': pokemontabel['weight'],
'height': pokemontabel['height']
})
(或在查询中需要时使用列表理解并构建该列表)。
sql = sql
可能是一个错字。
你有两个选择:
for p in pokemonlist:
cursor.execute(sql, p)
sql = 'INSERT INTO pokemon(id, name, weight, height) VALUES ' + ','.join(['(%(id)s, %(name)s, %(weight)s, %(height)s)'] * len(pokemonlist))
cursor.execute(sql, pokemonlist)
顺便说一句,我没有对此进行测试,您可能需要使用位置参数而不是命名参数。 如果你尝试一下,让我知道它是怎么回事。
pokemonlist.append(pokemon)
行应该缩进。 你也应该使用这个:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.