首页 > 解决方案 > SQLAlchemy-执行存储过程并填充类

问题描述

有没有办法执行存储过程并取回一个类?

我努力了:

session.query(MyClass).from_statement(...)

其中 myclass 定义为:

MyClass(Base):
     id = Column(Integer)
     name = Column(String)
    ...

我知道我应该放:

__tablename__ ‘sometable’

但是没有表,因为所有行都是存储过程调用的结果。你知道有什么办法可以解决这个问题吗?

标签: pythonsqlstored-proceduresormsqlalchemy

解决方案


迈克尔拜耳回购所有者

SQLAlchemy 目前不支持除 Oracle 之外的任何后端的 OUT 参数。为了现在使用 OUT 参数,您需要使用 DBAPI 函数 callproc(),请参阅http://initd.org/psycopg/docs/cursor.html#cursor.callproc

您的函数应如下所示:

def execproc(procname, engine, queryParams=[]):
    connection = engine.raw_connection()
    cursor = connection.cursor()
    try:
        cursor.callproc(procname, queryParams)
        rows = list(cursor.fetchall())
        cursor.close()
        connection.commit()
        return rows
    finally:
        connection.close()

推荐阅读