How to get Returned Query Object of PostgreSql Function in Python?

醉酒当歌 提交于 2021-01-29 06:25:43

问题


With pgsql function SelRec(integer) as defined below:

-- select record
CREATE OR REPLACE FUNCTION SelRec(_sno integer)
  RETURNS SETOF app_for_leave AS
$BODY$
    BEGIN
    RETURN QUERY
        SELECT * FROM "app_for_leave" WHERE "sno"=_sno;
    END
$BODY$
LANGUAGE 'plpgsql' VOLATILE;

I tried to call this function inside my python code, and expected the returned result as query object which furthermore I could get an individual value inside the query object.

import psycopg2

connection_string = 'postgresql://postgres:111111@localhost:5432/myDB'

conn = psycopg2.connect(connection_string)
cursor = conn.cursor()

obj = cursor.execute("select * from SelRec(1)");

conn.commit()

print obj # None

Yet, the result is None as if there is no data stored, but it does exist like below:

 sno | eid | ename |     sd     |     ed     | sid | status 
-----+-----+-------+------------+------------+-----+--------
   1 | 101 |       | 2013-04-04 | 2013-04-04 |   2 | f

My need is the obj return an query object which I would further call DataSet = obj.first(), and DataSet.status, ect for each individual value.

Any suggestion how I can achieve that? Thanks.


回答1:


I think it might be expected behavior.

From the docs http://initd.org/psycopg/docs/cursor.html#cursor.execute

The method returns None. If a query was executed, the returned values can be retrieved using fetch*() methods.

Try something like:

print(dir(obj), type(obj))
print(cursor.fetchall())



回答2:


I think you should try query given below. As you want to return set of rows.

select * from SelRec(1) as result (sno int, eid int, ename varchar, sd data_type, ed data_type, sid int, status boolean)


来源:https://stackoverflow.com/questions/52350645/how-to-get-returned-query-object-of-postgresql-function-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!