简体   繁体   English

在python中遍历MySQL的问题

[英]Problem iterating through MySQL in python

I just started learning python and am trying out projects.我刚开始学习 python 并且正在尝试项目。 I'm having a with my python code.我正在使用我的 python 代码。 What I want to do is to go through the rows in my table one after another and perform a specific task on each row.我想要做的是逐行浏览我的表中的行并在每一行上执行特定任务。 With an example, I have rows with multiple columns and three of the columns are con_access, exam and total.举个例子,我有多列的行,其中三列是con_access、examtotal。 Now I want to get sum of the values in con_access and exam columns and then put it in the total column.现在我想获得con_accessexam列中值的总和,然后将其放入总列中。 This calculation should done one by one.这个计算要一一进行。 The problem that am having is that the program goes to the last row, takes the total variable and populate every other with it我遇到的问题是程序转到最后一行,取总变量并用它填充其他变量

Below is my code下面是我的代码

def result_total():
    mdb = mysql.connector.connect(
        host="localhost",
        user="root",
        passwd="**************",
        database="majesty"
    )

    mycursor = mdb.cursor()
    # mycursor.execute("SELECT con_access, exam FROM students")
    mycursor.execute("SELECT CAST(con_access AS UNSIGNED) as con_access, CAST(exam AS UNSIGNED) as exam FROM students")
    rows = mycursor.fetchall()
    for row in rows:
        if row:
            total = row['con_access'] + row['exam']
            sql = "UPDATE students SET total = {}".format(total)
            mycursor.execute(sql)
            mdb.commit()

find total like below找到像下面这样的总数

total = row['con_access'] + row['exam']

If your datatype of con_access and exam in mysql table is varchar, you should cast it.如果你在 mysql 表中 con_access 和exam 的数据类型是varchar,你应该转换它。 Change the select query as follows.更改选择查询如下。

SELECT CAST(con_access AS UNSIGNED) as con_access, CAST(exam AS UNSIGNED) as exam FROM students

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM