【问题标题】:How to update MySQL faster by XML data?如何通过 XML 数据更快地更新 MySQL?
【发布时间】:2015-04-26 23:10:10
【问题描述】:

XMl 有 5000 条 'product' 记录,MySQL 中的表有 6000 条 'product' 记录,并不是所有的 xml 记录在数据库中都有等价的。我想更快地将数据从 xml 放到 mysql 中。怎么做?现在完成运行所需的时间是 11 秒。

db = MySQLdb.connect(host="",
                         user="",
                         passwd="",
                         db="")
cur = db.cursor()

DOMTree = minidom.parse(file.xml)
cNodes = DOMTree.childNodes

for i in cNodes[0].getElementsByTagName("product"):
    y = i.getElementsByTagName("code")[0].childNodes[0].toxml()
    z = i.getElementsByTagName("available")[0].childNodes[0].toxml()

    cur.execute("UPDATE product SET stock=%s WHERE ean=%s", (z, y))
db.commit()

【问题讨论】:

  • 您的问题不清楚,您的意思是“记录”而不是“职位”,您所说的更快是什么意思?更快/更快没有任何意义。

标签: python mysql sql


【解决方案1】:

Executemany 是你的朋友,你可以收集所有数据并一次推送它们,而不是在你的 for 循环中重复执行命令。

data = [
  ('A', 'blabla'),
  ('B', 'test1'),
  ('C', 'test2'),
]
stmt = "UPDATE product SET stock=%s WHERE ean=%s"
cur.executemany(stmt, data)

更多信息在这里: http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    相关资源
    最近更新 更多