Error “Previous SQL was not a query” in Python?

老子叫甜甜 提交于 2020-01-23 05:27:40

问题


I am trying to call a stored procedure in Python but it keeps giving me the following error. The procedure is written in SQL Server 2008 and I am using PyODBC to call the method and pass parameters to it.

import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+serveripaddr+';DATABASE='+database+';UID='+userid+';PWD='+password+'')
cursor = cnxn.cursor()
cursor.execute("{call p_GetTransactionsStats('KENYA', '41')}")
rows = cursor.fetchall()

The last line results in the following exception:

ProgrammingError: No results.  Previous SQL was not a query.

What could be the problem here?


回答1:


Here's what happens. The stored procedure contains several steps. When it is executed from the SQL Server Management studio, it is easy to see how each step results in a separate message such as "(3 row(s) affected)", and only the very last step produces the response.

Apparently, when invoked via pyodbc cursor, each of those separate steps produces a separate resultset, where all the resultsets, but the very last one, contain no data that could be read via fetchall().

Hence, one option to solve the problem is to iterate over these resultsets using nextset() until you find one which does produce the result, e.g.:

while cursor.nextset():   # NB: This always skips the first resultset
    try:
        results = cursor.fetchall()
        break
    except pyodbc.ProgrammingError:
        continue

A nicer option is, as mentioned in a different answer, to use the SET NOCOUNT ON; directive, which seems to prevent all of the intermediate, empty (# rows affected) resultsets. The directive can be simply prepended to the proc invocation, for example:

cursor.execute("set nocount on; exec MyStoredProc ?", some_parameter)
results = cursor.fetchall()



回答2:


Can you add SET NOCOUNT ON to you SP and try if you can not modify SP, first execute this statement xand then call SP




回答3:


For stored procedures, you don't need .fetchall(). I had a similar issue and taking away that tag cleared it up.



来源:https://stackoverflow.com/questions/41302866/error-previous-sql-was-not-a-query-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!