【问题标题】:How to retrieve SQL Server RAISERROR (or PRINT) messages?如何检索 SQL Server RAISERROR(或 PRINT)消息?
【发布时间】:2021-08-24 18:00:59
【问题描述】:

我正在尝试使用 PyODBC 从 Python 中的 SQL Server 的 Raiserror 获取警告消息。

故意降低严重性,因为它充当打印功能,但不必等到查询完成后再打印。

我期望的输出是这样的:

*Test Message*
|col1|
|:-|
|1|

这是我的代码:

import pyodbc

conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=ECH-DWPROD02;DATABASE=Test;Trusted_Connection=yes;')
cursor = conn.cursor()

cursor.execute("SET NOCOUNT ON; RAISERROR('Test Message',0,1) WITH NOWAIT; select 1 as col1")
cursor.fetchall()

【问题讨论】:

标签: python sql-server python-3.x pyodbc


【解决方案1】:

Cursor.messages 是对 pyodbc(v4.0.31 - 2021 年 7 月)的一个相当新的补充。它允许我们通过 PRINT 和 RAISERROR 检索从 SQL Server 存储过程发出的消息。

请注意,此类消息构成来自服务器的“结果”,因此如果返回它们,则必须调用 .nextset() 以检索其他结果,否则“先前的 SQL 不是查询”。会发生错误:

crsr.execute("""\
SET NOCOUNT ON; 
RAISERROR('Test Message',0,1) WITH NOWAIT; 
select 1 as col1
""")
print(crsr.messages)
# [('[01000] (50000)', '[Microsoft][ODBC SQL Server Driver][SQL Server]Test Message')]
crsr.nextset()  # required before .fetchall()
print(crsr.fetchall())
# [(1, )]

【讨论】:

    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多