为什么不会这个循环?

Why wont this loop?

Newby 使用 mariadb 完成 python 和 sql。 为什么不会这个循环?它只更新第一条记录。我很擅长这个...

cursor1.execute("select recordid, mvavgvol, quote_usd_volume_change_24h from pumped")
records = cursor1.fetchall()

for x in records:

            rid = (x[0])
            m = (x[1])
            o = (x[2])

            if (m >= o):
                  result = 0
            else:
                  result = 1

upd_data=(result,rid)
sql1 = ("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s")
cursor2.execute(sql1,upd_data)
conn.commit()
conn = msql.connect(host=Host,port=Port, user=User, password=Password, database=database)
cursor1 = conn.cursor()
cursor2 = conn.cursor()

cursor1.execute("select recordid, mvavgvol, quote_usd_volume_change_24h from pumped")
records = cursor1.fetchall()

for x in records:

            rid = (x[0])
            m = (x[1])
            o = (x[2])

            if (m >= o):
                  result = 0
                  cursor2.execute("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s",(result, rid))
                  conn.commit()

            else:
                  result = 1
                  cursor2.execute("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s",(result, rid))
                  conn.commit()

由于您要获取多行,因此您必须将获取的值存储在一个数组中,并改为使用游标的 executemany() 方法。

data= []
for x in records:
            rid = (x[0])
            result= int(x[1] > x[2])
            data+= [(result, rid)]

cursor.executemany(UPDATE pumped SET  mvavgvolcheck = %s WHERE recordid = %s", data);

当使用 mariadb python 模块 (MariaDB Connector/Python) 时,这更有效,因为它减少了网络流量:而不是在循环中发送 n 个更新命令(其中 n 是行数在 table 中)只有一个命令会被发送到服务器。