注册 登录
编程论坛 Python论坛

运行结果只显示最后一行第218行,前面的不显示,错在哪里?

shuxie95 发布于 2023-04-11 16:08, 93 次点击
import pymysql
sql = "select id,name,category,price,category1,publish_time from hadoopdata"
def main():
    try:
        db = pymysql.connect(host="localhost",user="root",password="123456",database="pysql")
        cursor = db.cursor()
        cursor.execute(query=sql)
        for user_row in cursor.fetchall():
            id = user_row[0]
            name =user_row[1]
            category = user_row[2]
            price = user_row[3]
            category1 = user_row[4]
            publish_time = user_row[5]
        print("%s %s %s %s %s %s " % (id,name,category,price,category1,publish_time))
    except exception:
        print("error"+traceback.format_exc())
    finally:
        db.close()
if __name__=="__main__":
    main()

#运行结果只显示最后一行第218行的数据,前面的不显示,错在哪里?表在MYSQL里查询此表格是有218条数据的
#218 自粘聚合物改性沥青防水卷材 -218 -218.00 -218 2019-08-01
#进程已结束,退出代码0
2 回复
#2
东海ECS2023-04-11 18:52

问题出在for循环中,循环体内的print语句应该与for循环同级别,即在for循环内部,而不是在循环外部。因为在循环外部,只会输出最后一次循环的结果。

修改后的代码应该是这样的:

程序代码:

import pymysql

sql = "select id,name,category,price,category1,publish_time from hadoopdata"

def main():
    try:
        db = pymysql.connect(host="localhost",user="root",password="123456",database="pysql")
        cursor = db.cursor()
        cursor.execute(query=sql)
        for user_row in cursor.fetchall():
            id = user_row[0]
            name =user_row[1]
            category = user_row[2]
            price = user_row[3]
            category1 = user_row[4]
            publish_time = user_row[5]
            print("%s %s %s %s %s %s " % (id,name,category,price,category1,publish_time))
    except Exception as e:
        print("error: " + str(e))
    finally:
        db.close()

if __name__=="__main__":
    main()


这样就可以输出所有查询结果了。另外,原代码中except exception应该改为except Exception,因为异常类型应该是Exception而不是exception。
#3
shuxie952023-04-12 09:46
回复 2楼 东海ECS
谢谢,太感谢了!
1