gpt4 book ai didi

python - 在线性时间内动态更新 Python 中的 MySQL 表

转载 作者:行者123 更新时间:2023-12-04 09:07:17 25 4
gpt4 key购买 nike

我有一个包含大量条目的现有表,我想为每一行计算一个新列。我只找到了以下解决方案。这有效,但速度很慢,因为它需要扫描表的大部分条目。
我想要的是一种方法:

  • 阅读一行
  • 根据行
  • 的内容计算新列的值
  • 更新到数据库

  • 这样它只会通过表一次并且具有线性复杂性。
            cursor.execute("SELECT tweet FROM Table")
    row = cursor.fetchone()
    while row is not None:
    vader = analyser.polarity_scores(row)
    sentiment_vader = vader["compound"]
    cursor2.execute(
    "UPDATE Table SET sentiment_vader = %s WHERE tweet = %s LIMIT 1",
    (sentiment_vader, row[0]))
    kody.cnx.commit()
    row = cursor.fetchone()

    最佳答案

    我看到的主要性能问题是您不应该为每行更新提交,因为这会增加开销。您应该在 while 结束时或一批之后提交。

    while row is not None:
    ...
    else:
    kody.cnx.commit()
    另外,如果 tweet列未编入索引只需在该列上创建索引,以便在更新期间不进行表扫描。

    关于python - 在线性时间内动态更新 Python 中的 MySQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63419111/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com