【问题标题】:How to Fetch Data from cursor in Postgres with Flask, SQLAlchemy or psycopg2如何使用 Flask、SQLAlchemy 或 psycopg2 从 Postgres 中的游标中获取数据
【发布时间】:2018-03-04 15:03:24
【问题描述】:

我正在使用 Flask 并在 Postgres 数据库上创建过程,例如

CREATE OR REPLACE FUNCTION "public"."   "()
  RETURNS "pg_catalog"."refcursor" AS $BODY$
DECLARE
    ref refcursor;
BEGIN
    OPEN ref FOR select posts.*, users.username, users.name from posts left join users on posts.user_id = users.id;
    RETURN ref;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100

在我的代码中使用 SQLAlchemy

connection.execute("SELECT home_data()").fetchall()

它将光标名称 home_data 返回为“未命名的门户 1”

psycopg2

conn = psycopg2.connect(host="localhost",database="xxxx", user="xxxx", password="xxxx")

def home_pro():
        cur = conn.cursor()
        return cur.callproc('home_data')

并且这段代码没有返回任何内容。

请帮助我如何从我的程序中获取数据,我在互联网上搜索但没有得到任何东西。

【问题讨论】:

    标签: python postgresql sqlalchemy psycopg2


    【解决方案1】:

    我得到答案,

       res = cur.callproc('getPerson')
       row = cur.fetchone()
    
       cur.execute(f'FETCH ALL IN "{row[0]}"')
       results = cur.fetchall()
    

    【讨论】:

    • 太棒了!谢谢@vipin
    猜你喜欢
    • 1970-01-01
    • 2020-08-13
    • 2012-05-02
    • 2021-05-01
    • 2012-05-22
    • 2017-06-05
    • 2014-05-09
    • 1970-01-01
    相关资源
    最近更新 更多