我无法在python中获取光标

问题描述 投票:2回答:1

我正在使用postgresql函数并从python调用。但是我无法获取光标。

这是我的postgresql函数。

  CREATE LANGUAGE plpgsql;
        create or replace FUNCTION getPerson() returns REFCURSOR
           AS $$
        DECLARE
        p_cursor refcursor;   
        BEGIN
           open p_cursor FOR
           select m.name AS name, m.surname AS surname from person m;
           RETURN p_cursor;
        END; $$
        LANGUAGE plpgsql;

这是我的python函数

 import psycopg2    
    try:
       conn = psycopg2.connect(database="dt", user = "us", password = "pass", host = "127.0.0.1", port = "5432")

       cur = conn.cursor()
       res = cur.callproc('getPerson')
       result = cur.fetchall()

       for row in result:
           print "printed row"
           print row   

       conn.commit()
       cur.close()
       conn.close()  

    except:     
        print "error"

结果:

printed row
('<unnamed portal 1>',)
python sql postgresql
1个回答
1
投票

正如Abelisto所提到的,在调用过程时,您需要先获取游标的名称。使用psycopg2它是:

res = cur.callproc('getPerson')
row = cur.fetchone()

然后继续另一个FETCH查询:

cur.execute(f'FETCH ALL IN "{row[0]}"') #Note: python 3.6
results = cur.fetchall()

完整代码:

import psycopg2    
try:
   conn = psycopg2.connect(database="dt", user = "us", password = "pass", host = "127.0.0.1", port = "5432")
   cur = conn.cursor()

   res = cur.callproc('getPerson')
   row = cur.fetchone()

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

   for row in results:
       print row   

   cur.close()

except (Exception, psycopg2.DatabaseError) as error:
    print(error)
finally:
    if conn is not None:
        conn.close()
        print('Database connection closed.')
© www.soinside.com 2019 - 2024. All rights reserved.