代码之家  ›  专栏  ›  技术社区  ›  vipin

如何使用Flask、SQLAlchemy或psycopg2从Postgres中的游标获取数据

  •  3
  • vipin  · 技术社区  · 7 年前

    我正在使用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
    

    在我的代码中 SQL炼金术

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

    它将光标名称home\u 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')
    

    此代码不返回任何值。

    请帮助我如何从我的程序中获取数据,我在互联网上搜索了这个,但什么都没有得到。

    1 回复  |  直到 7 年前
        1
  •  3
  •   vipin    7 年前

    我得到了答案,

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