2014-12-04 66 views
0

内有Postgres的存储功能:我如何使用Postgres的游标Python代码

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

然后在Python我想调用的程序使用psycopg2的exapmle按行获取returnung光标一行。 有没有什么办法可以做到这一点?谢谢。

回答

3

这是比较容易让psycopg2server side cursor创建工作just by naming it

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

要使用返回光标功能执行它像往常一样:

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

然后搭上返回光标与命名光标:

named_cursor = conn.cursor(name='cursor_x') 
for row in named_cursor: 
    print row 
+0

谢谢,我知道服务器端curso rs,但是在这里我们需要以某种方式利用DB中已有的存储函数。 – 2014-12-04 12:03:36

+0

@ИванСудос更新 – 2014-12-04 12:11:50