Python 来自 XML 的数据库更新仅更新最后一条记录

Python Database update from XML only updates last record

我已经编写了一个脚本来更新我的 mysql 数据库中的股票,但我只从 xml 更新了最后一条记录,我正在通过一条正确知道并喜欢的隧道寻找有一双新鲜的眼睛看着它。

import requests
import xml.etree.ElementTree as ET
from lxml import etree
from getpass import getpass
from mysql.connector import connect, Error
r = requests.get('http://api.edc.nl/xml/eg_xml_feed_stock.xml')

root = ET.fromstring(r.content)

for x in root.iter('product'):
    id = x.find('productid').text
    qty = x.find('qty').text


try:
    with connect(
        host="my host",
        user=input("Enter username: "),
        database="my database",
        password=getpass("Enter password: "),


    ) as connection:
        query = "UPDATE `ps_stock_available` SET `quantity` = " + \
            qty + " WHERE `id_product` = " + id + ";"
        with connection.cursor() as cursor:
            cursor.execute(query)
            connection.commit()
            #result = cursor.fetchall()
            # for row in result:
            print(query)
except Error as e:
    print(e)

更新 table 的代码需要在 for 循环内。否则它只在循环完成后运行一次,并使用变量的最后值。

query = "UPDATE `ps_stock_available` SET `quantity` = %s WHERE `id_product` = %s"

try:
    with connect(
        host="my host",
        user=input("Enter username: "),
        database="my database",
        password=getpass("Enter password: "),
    ) as connection:
        with connection.cursor() as cursor:
            for x in root.iter('product'):
                prod_id = x.find('productid').text
                qty = x.find('qty').text
                cursor.execute(query, (qty, prod_id))
            connection.commit()
except Error as e:
    print(e)

不要将id用作变量,它是内置函数的名称。