【问题标题】:How to use postgres cursor within Python code如何在 Python 代码中使用 postgres 游标
【发布时间】:2014-12-04 11:20:39
【问题描述】:

我在 postgres 中有一个存储函数:

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

然后在 Python 中,我想调用过程来逐行获取返回游标,例如使用 psycopg2。 有没有办法做到这一点?谢谢。

【问题讨论】:

    标签: python postgresql stored-procedures cursor psycopg2


    【解决方案1】:

    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
    

    【讨论】:

    • 谢谢,我知道服务器端游标,但在这里我们需要以某种方式利用数据库中现有的存储函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 2020-09-01
    • 1970-01-01
    相关资源
    最近更新 更多