Houy Narun
Houy Narun

Reputation: 1725

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

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.

Upvotes: 1

Views: 4217

Answers (2)

Bharti Mohane
Bharti Mohane

Reputation: 706

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)

Upvotes: 0

jmunsch
jmunsch

Reputation: 24089

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())

Upvotes: 1

Related Questions