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

使用Python PrettyTable无法打印SQL表内容,仅显示表头求助

问题原因

你在display()函数里先调用了mycursor.fetchall(),这会把游标指向的结果集全部读取出来,游标位置直接移动到结果末尾。之后再用from_db_cursor(mycursor)时,游标已经没有剩余数据可以读取,所以只能显示表头,看不到表中存储的数据。

解决方案

有两种简单的修复方式:

方式一:移除多余的fetchall()调用

直接删除result=mycursor.fetchall()这一行,因为from_db_cursor会自动从游标获取查询结果:

def display():
    mycursor.execute("select * from student")
    print("""
    no OF RECORDS IS: """,mycursor.rowcount)
    print("""
              """)
    if mycursor.rowcount>0:
        x = from_db_cursor(mycursor)
        print(x)
    else:
        print("the table is empty")

方式二:用查询结果手动构建表格

如果需要保留fetchall()的结果用于其他逻辑,可以用from_rows方法结合表头来构建表格:

def display():
    mycursor.execute("select * from student")
    result=mycursor.fetchall()
    # 获取表头字段名
    headers = [i[0] for i in mycursor.description]
    print("""
    no OF RECORDS IS: """,len(result))
    print("""
              """)
    if len(result)>0:
        x = from_rows(result, headers=headers)
        print(x)
    else:
        print("the table is empty")
额外提示
  • mysql.connector的游标默认是只读且单向的,一旦读取过数据,游标不会自动重置,除非重新执行查询。
  • 若需要多次读取游标数据,可以使用带缓冲的游标(mydb.cursor(buffered=True)),但上述两种方法更直接解决当前问题。

内容的提问来源于stack exchange,提问作者Albin Saji

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 15:05:31