Python读取MySQL数据打印失败,输出None如何解决?
解决Python读取MySQL数据输出None的问题
你的代码问题出在两点:
cursor.execute(query)的返回值不是查询结果(部分驱动下执行SELECT会返回None或匹配行数),你错误地打印了这个返回值a- 遍历游标时已经解构出了每行的字段,应该打印这些字段而非
a
修正后的代码如下:
cursor = cnx.cursor() query = 'select * from test order by Age asc;' cursor.execute(query) # 遍历游标,打印每行的字段内容 for (Name, Last_name, Home_number, Age, Gender) in cursor: print(Name, Last_name, Home_number, Age, Gender) cnx.close()
如果需要先把所有结果存储起来再处理,可以用fetchall()方法:
cursor = cnx.cursor() query = 'select * from test order by Age asc;' cursor.execute(query) # 获取全部查询结果 all_results = cursor.fetchall() for row in all_results: print(row) # 或者按字段解构打印 for (Name, Last_name, Home_number, Age, Gender) in all_results: print(f"姓名: {Name}, 姓氏: {Last_name}, 家庭电话: {Home_number}, 年龄: {Age}, 性别: {Gender}") cnx.close()
额外提醒:建议在SQL语句中明确指定字段,避免表结构变化导致字段顺序不匹配的问题,比如:
select Name, Last_name, Home_number, Age, Gender from test order by Age asc;
内容的提问来源于stack exchange,提问作者Taha
相关产品推荐
相关产品推荐

