PL/PGSQL 函数,访问 psycopg2 返回的结果集时遇到问题
我有这个 pl/pgsql 函数:
CREATE OR REPLACE FUNCTION get_result(id integer) RETURNS SETOF my_table AS $
DECLARE
result_set my_table%ROWTYPE;
BEGIN
IF id=0 THEN
SELECT INTO result_set my_table_id, my_table_value FROM my_table;
ELSE
SELECT INTO result_set my_table_id, my_table_value FROM my_table WHERE my_table_id=id;
END IF;
RETURN;
END;
$ LANGUAGE plpgsql;
我正在尝试将其与 Python 的 psycopg2 库一起使用。这是 python 代码:
import psycopg2 as pg
conn = pg.connect(host='myhost', database='mydatabase', user='user', password='passwd')
cur = conn.cursor()
return cur.execute("SELECT * FROM get_result(0);") # returns NoneType
但是,如果我只是执行常规查询,我会得到正确的行集:
...
return cur.execute("SELECT my_table_id, my_table_value FROM mytable;") # returns iterable result set
我的 pl/pgsql 函数显然有问题,但我似乎无法正确处理。
我还尝试使用
RETURN result_set;
而不是仅
RETURN
在 plpgsql 函数的第 10 行中使用,但从 postgres 收到错误。
I have this pl/pgsql function:
CREATE OR REPLACE FUNCTION get_result(id integer) RETURNS SETOF my_table AS $
DECLARE
result_set my_table%ROWTYPE;
BEGIN
IF id=0 THEN
SELECT INTO result_set my_table_id, my_table_value FROM my_table;
ELSE
SELECT INTO result_set my_table_id, my_table_value FROM my_table WHERE my_table_id=id;
END IF;
RETURN;
END;
$ LANGUAGE plpgsql;
I am trying to use this with Python's psycopg2 library. Here is the python code:
import psycopg2 as pg
conn = pg.connect(host='myhost', database='mydatabase', user='user', password='passwd')
cur = conn.cursor()
return cur.execute("SELECT * FROM get_result(0);") # returns NoneType
However, if i just do the regular query, I get the correct set of rows back:
...
return cur.execute("SELECT my_table_id, my_table_value FROM mytable;") # returns iterable result set
Theres obviously something wrong with my pl/pgsql function, but I can't seem to get it right.
I also tried using
RETURN result_set;
instead of just
RETURN
in the 10th line of my plpgsql function, but got an error from postgres.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请阅读更改“RETURN;”时出现的错误到“返回结果集;”。然后阅读以下内容 - "38.6.1.2. RETURN下一步并返回查询”。
提示 - 在你的情况下你需要“RETURN QUERY”。
Please read the error you're getting when you change "RETURN;" to "RETURN result_set;". And then read the following - "38.6.1.2. RETURN NEXT and RETURN QUERY".
A hint - in your case you need "RETURN QUERY".