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

Python调用返回多结果集的MySQL存储过程并格式化为表格

解决MySQL存储过程多结果集转命令行表格输出问题

报错原因分析

  • "Error: No result set to fetch from":存储过程包含多条SELECT语句时,执行后会生成多个结果集,若未切换到下一个结果集就直接调用fetch方法,就会触发该错误。
  • "TypeError: 'NoneType' object is not iterable":当尝试迭代不存在的结果集(比如已处理完所有结果集后仍调用fetch),会返回None,进而引发迭代错误。

处理MySQLCursorBufferedDict生成表格

可以用prettytable库快速将字典格式的结果集转换成对齐的命令行表格,无需手动处理列对齐和格式排版。

可行解决方案代码

import mysql.connector
from mysql.connector.cursor import MySQLCursorBufferedDict
from prettytable import PrettyTable

# 数据库连接配置
db_config = {
    'user': 'your_username',
    'password': 'your_password',
    'host': 'your_host',
    'database': 'your_db'
}

try:
    # 建立连接,使用缓冲字典游标
    conn = mysql.connector.connect(**db_config)
    cursor = conn.cursor(cursor_class=MySQLCursorBufferedDict)
    
    # 调用存储过程(带参数的话传入元组,如('param1', 'param2'))
    cursor.callproc('your_stored_procedure_name')
    
    # 遍历所有结果集
    result_set_count = 0
    while True:
        try:
            # 切换到下一个结果集
            cursor.nextset()
            results = cursor.fetchall()
            
            if not results:
                break
            
            # 生成格式化表格
            table = PrettyTable()
            table.field_names = results[0].keys()
            for row in results:
                table.add_row(row.values())
            
            # 打印结果集表格
            print(f"=== 结果集 {result_set_count + 1} ===")
            print(table)
            result_set_count += 1
            
        except mysql.connector.errors.InterfaceError:
            # 无更多结果集时退出循环
            break

finally:
    # 关闭游标与连接
    if cursor:
        cursor.close()
    if conn:
        conn.close()

关键说明

  1. MySQLCursorBufferedDict会缓冲结果集,且每行数据以字典形式返回,方便直接提取列名和对应值。
  2. 通过cursor.nextset()逐个切换结果集,直到捕获到无结果集的异常后退出循环。
  3. prettytable自动处理列对齐,输出的表格格式规整,可直接用于命令行打印或后续邮件内容拼接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 12:54:57