2

I have a stored function in postgres:

CREATE FUNCTION return_curs() RETURNS refcursor AS $$
BEGIN
    OPEN cursor_x FOR SELECT col FROM table_y;
    RETURN cursor_x;
END; $$

Then in Python I want to invoke the procedure to fetch returnung cursor row by row for exapmle using psycopg2. Are there any way to perform this? Thanks.

1 Answer 1

4

It is easier to let psycopg2 do the server side cursor creation work just by naming it:

cursor = conn.cursor(name='cursor_x')
query = "select * from t"
cursor.execute(query)
for row in cursor:
    print row

To use a returning cursor function execute it as usual:

cur = conn.cursor()
cur.callproc('return_curs')

Then catch the returned cursor with a named cursor:

named_cursor = conn.cursor(name='cursor_x')
for row in named_cursor:
    print row
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I know about server side cursors, but here we need to utilize somehow existing stored functions in the DB.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.