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

Python脚本执行MSSQL存储过程成功但无法获取返回结果

问题分析与解决方案

可能的原因

  • 多结果集未处理:你的存储过程可能在返回目标数据前,先输出了其他内容(比如PRINT语句的消息、中间查询的输出)。SSMS会自动遍历并显示所有结果集,但pyodbc默认只读取第一个结果集,如果第一个是空的,就会出现执行成功但拿不到数据的情况。
  • 参数传递方式不当:直接用字符串拼接生成执行语句,可能导致参数类型不匹配(比如存储过程期望整数类型,但你传了字符串格式的'45'),或者触发存储过程内部的逻辑分支,导致无数据返回。

修改后的脚本

下面的脚本同时解决了多结果集处理和参数化调用的问题:

import pyodbc

# Database connection details
driver = '{SQL Server Native Client 11.0}'
server = 'MIS-SRV'
database = 'XStudio_Historian'
username = 'username'
password = 'database_password'

# Stored procedure to execute
stored_proc_name = 'getlive_value'
parameter = '45'  # 如果存储过程参数是整数类型,直接传45即可

# Connection string
conn_str = f'DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password}'

try:
    # Connect to the database
    conn = pyodbc.connect(conn_str)
    print("Connected to the database.")

    # Create a cursor
    cursor = conn.cursor()

    # 推荐:使用参数化调用存储过程,避免SQL注入和参数格式问题
    cursor.execute(f"EXEC {database}.[dbo].{stored_proc_name} ?", (parameter,))
    
    print("Stored procedure executed successfully.")

    # 处理所有结果集,直到没有更多结果
    while True:
        rows = cursor.fetchall()
        if not rows:
            break
        for row in rows:
            print(row)
        # 移动到下一个结果集
        if not cursor.nextset():
            break

    # Close cursor and connection
    cursor.close()
    conn.close()
    print("Connection closed.")
    
except pyodbc.Error as ex:
    print(f"Error: {ex}")

额外说明

  1. 参数类型匹配:确认存储过程getlive_value的参数类型,如果是INT,把parameter = '45'改成parameter = 45,参数化调用会自动处理类型转换,避免格式错误。
  2. 优化存储过程:如果问题仍存在,可以在存储过程开头添加SET NOCOUNT ON;,避免返回受影响行数的消息干扰结果集读取。

内容的提问来源于stack exchange,提问作者Ranjit Singh Shekhawat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 21:44:51