You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 09:33:14