【问题标题】:How do I add multiple items with a for loop in Python to a SQL table?如何在 Python 中使用 for 循环将多个项目添加到 SQL 表中?
【发布时间】: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()

【问题讨论】:

    标签: python sql json


    【解决方案1】:

    pokemonlist.append(pokemon) 应该是循环的一部分,你也不需要将它分配给变量,只需这样做:

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

    (或在查询中需要时使用列表推导并构建该列表)。

    sql = sql 可能是一个错字。

    你有两个选择:

    1. 为每个口袋妖怪循环执行:
    for p in pokemonlist:
       cursor.execute(sql, p)
    
    1. 或者创建一个动态 sql 语句,其中值部分 '(%(id)s, %(name)s, %(weight)s, %(height)s)' 重复 len(pokemonlist) 次,以逗号分隔并将 pokemonlist 传递给执行:
    sql = 'INSERT INTO pokemon(id, name, weight, height) VALUES ' + ','.join(['(%(id)s, %(name)s, %(weight)s, %(height)s)'] * len(pokemonlist))
    cursor.execute(sql, pokemonlist)
    

    我没有对此进行测试,顺便说一句,您可能需要使用位置参数而不是命名参数。如果您尝试一下,请告诉我结果如何。

    【讨论】:

      【解决方案2】:

      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)
      

      【讨论】:

        猜你喜欢
        • 2023-01-07
        • 1970-01-01
        • 2021-03-27
        • 2020-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-21
        相关资源
        最近更新 更多