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

Flask中cursor.callproc()仅返回存储过程首个查询结果的问题

问题

在Flask中使用cursor.callproc()调用包含两个SELECT语句的MySQL存储过程fetchAuctionAndProduct时,仅能获取第一个SELECT语句的结果集,第二个结果集无法获取。

存储过程代码:

DELIMITER //
CREATE PROCEDURE fetchAuctionAndProduct()
BEGIN
    SELECT product_category_name from product_category;
    SELECT auction_id FROM auction;
END //
DELIMITER ;

原Flask调用核心代码:

procursor = mysql.connection.cursor()
procursor.callproc('fetchAuctionAndProduct')
result = procursor.fetchall()
print(result)
解决方案

MySQL存储过程返回多个结果集时,游标默认仅指向第一个结果集。要获取所有结果集,需调用游标对象的nextset()方法切换到下一个结果集,直到nextset()返回None(表示无更多结果集)。

步骤说明

  1. 执行存储过程后,先获取第一个结果集
  2. 调用procursor.nextset()切换到下一个结果集
  3. 获取第二个结果集
  4. 重复步骤2-3,直到遍历完所有结果集

修改后的核心代码示例

procursor = mysql.connection.cursor()
procursor.callproc('fetchAuctionAndProduct')

# 获取第一个结果集
result1 = procursor.fetchall()
print("第一个结果集:", result1)

# 切换并获取第二个结果集
if procursor.nextset():
    result2 = procursor.fetchall()
    print("第二个结果集:", result2)

procursor.close()

适配完整登录接口的代码片段

elif user:
    procursor = mysql.connection.cursor()
    procursor.callproc('fetchAuctionAndProduct')
    
    # 获取商品分类结果集
    category_result = procursor.fetchall()
    print("商品分类:", category_result)
    
    # 切换并获取拍卖ID结果集
    if procursor.nextset():
        auction_result = procursor.fetchall()
        print("拍卖ID:", auction_result)
    
    procursor.close()
    mesage = 'Logged in successfully !'
    return render_template('user.html', mesage = mesage)

多结果集通用遍历方式

如果存储过程返回更多结果集,可通过循环遍历所有结果:

procursor.callproc('fetchAuctionAndProduct')
all_results = []
while True:
    current_result = procursor.fetchall()
    if current_result:
        all_results.append(current_result)
    # 切换到下一个结果集,无结果时退出循环
    if not procursor.nextset():
        break
print("所有结果集:", all_results)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:45:20