3

I'm stuck -- I have the following python script with SQL alchemy which I've been using quite successfully for several other purposes.

import sqlalchemy
from sqlalchemy import MetaData
from sqlalchemy.orm import *

engine = sqlalchemy.create_engine("this line of code would provide credentials to the     database")
connection = engine.connect()
session = sessionmaker(bind=engine)
result = connection.execute(sqlquery)

for row in result: print row

Recently though I discovered that if my 'sqlquery' contains an @Declare MyTable statement I get the error:

"This result object does not return rows. "
sqlalchemy.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically.

Here is my SQL query which works fine in SSMS but will not execute when I try to execute it using SQLAlchemy

DECLARE @USER TABLE
(
    UserID INT
    , StatsVals INT
)

INSERT INTO @USER (UserID, StatsVals)
    SELECT TOP 10 u.UserID
    , u.StatsVals
    FROM UserProfile u

SELECT * FROM @USER

Does anyone know why SQLAlchemy would be giving me this error? What should I do to fix this?

4

2 回答 2

4

当 DBAPI 在游标上执行时,如果存在结果,则需要存在一个名为的属性cursor.description。如果不是,SQLAlchemy 知道没有结果可以返回。

在这种情况下,这可能是 DBAPI 的问题,除非这种用法属于游标上的“多个结果集”范围。SQLAlchemy 目前还没有直接支持多个结果集。如果是这种情况,您需要直接使用 DBAPI 游标并调用.nextset()以获取结果。您可以通过以下方式获得:

connection = engine.raw_connection()
cursor = connection.cursor()

(有关 cursor.nextset() 如何工作的文档,请访问 http://www.python.org/dev/peps/pep-0249/

否则,你真的需要联系 DBAPI 作者,看看你在这里做的事情是否真的可行。我猜这是 pyodbc,即使您没有指定您使用的后端。如果是这样,您可以通过http://code.google.com/p/pyodbc/与他们联系。

于 2012-02-14T02:12:53.103 回答
1

要更具体地了解 zzzeek 答案,您应该执行类似的操作

from pyodbc import ProgrammingError
from sqlalchemy import create_engine

# do the connection
engine = create_engine('mssql+pyodbc://user:password@SERVERNAME/DatabaseName?driver=SQL Server')
connection = engine.raw_connection()
cursor = connection.cursor()

# do the query
cursor.execute(query)

# processing it
while True:
    try:
        result = cursor.fetchall()

        # ... do something with result

        if not cursor.nextset(): # trying to get next set
            break
    except ProgrammingError as ex:
        pass

这有助于我使用具有大量临时表和声明的非常复杂的 MSSQL

于 2017-06-29T18:52:44.807 回答