【问题标题】:Python Database update from XML only updates last record来自 XML 的 Python 数据库更新仅更新最后一条记录
【发布时间】:2021-04-17 09:42:26
【问题描述】:

我已经编写了一个脚本来更新我的 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)

【问题讨论】:

  • 不要使用字符串连接替代查询,使用占位符和参数。
  • 是的,每天都在学习,谢谢。但这与最后的记录有关吗?我认为占位符和参数正在使用这个 %s?

标签: python xml-parsing mysql-python


【解决方案1】:

更新表格的代码需要在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用作变量,它是一个内置函数的名称。

【讨论】:

  • 谢谢,工作就像一个魅力,我已经更新了脚本,因为 id 是 qty 并且 qty 是 id :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
相关资源
最近更新 更多