[英]How to get a SQL Server stored procedure return value using pyodbc?
My team's using a python-based wiki server that calls stored procedures on a SQL Server database.我的团队正在使用基于 python 的 wiki 服务器,该服务器调用 SQL Server 数据库上的存储过程。 Ideally, we'd like to return integer values (1,0,-1) from the stored procedure to show basic results.
理想情况下,我们希望从存储过程返回整数值 (1,0,-1) 以显示基本结果。
According to a 2008 thread on Google Groups<\/a> , return values aren't supported by pyodbc, so the alternative is to SELECT the result as a row and check it instead.根据
Google Groups 上的 2008 线程<\/a>,pyodbc 不支持返回值,因此替代方法是将结果选择为一行并进行检查。 Is that still the case?
还是这样吗? Is there a (supported and documented) programmatic way to check the return value from SQL stored procedures?
是否有(支持和记录的)编程方式来检查 SQL 存储过程的返回值? (If so, please add a current reference or example.)
(如果是这样,请添加当前参考或示例。)
I'm using this: 我正在使用这个:
def CallStoredProc(conn, procName, *args):
sql = """DECLARE @ret int
EXEC @ret = %s %s
SELECT @ret""" % (procName, ','.join(['?'] * len(args)))
return int(conn.execute(sql, args).fetchone()[0])
It only works on SQL Server (or maybe Sybase), but it's a decent workaround. 它只适用于SQL Server(或Sybase),但它是一个不错的解决方法。
I added the following to get it to work in my application: 我添加了以下内容以使其在我的应用程序中工作:
def CallStoredProc(conn, procName, *args):
sql = """SET NOCOUNT ON;
DECLARE @ret int
EXEC @ret = %s %s
SELECT @ret""" % (procName, ','.join(['?'] * len(args)))
return int(conn.execute(sql, args).fetchone()[0])
Here's some relevant information: http://code.google.com/p/pyodbc/wiki/StoredProcedures 以下是一些相关信息: http : //code.google.com/p/pyodbc/wiki/StoredProcedures
It sounds like return values are still not supported, so you'll need to use a SELECT
. 听起来仍然不支持返回值,因此您需要使用
SELECT
。
I used similar solution of Gabe and I needed Named parameters:我使用了 Gabe 的类似解决方案,我需要命名参数:
def call_stored_procedure(conn, procName, **args):
query = ""
for key, value in args.items():
query = query+',@'+key+'='+'\"'+str(value)+'\"'
query = query[ 1:]
sql = """ SET QUOTED_IDENTIFIER OFF
SET ANSI_NULLS ON
SET NOCOUNT ON
DECLARE @ret int
EXEC @ret = %s %s
COMMIT
SELECT @ret""" % (procName, query)
id = conn.execute(sql).fetchone()[0]
call_stored_procedure(conn, "MY_StoredProcedure", **payload)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.