首页 > 解决方案 > 在 psycopg2 中移动命名光标

问题描述

我在 psycopg2 中使用命名游标。如何重置光标从0开始?我使用了以下代码,但没有效果并且有错误。

with conn.cursor(name="curname") as cursor:
    cursor.itersize = 100
    cursor.execute("MOVE ABSOLUTE 0 IN curname",)

错误:

LINE 1: DECLARE "curname" CURSOR WITHOUT HOLD FOR MOVE ABSOLUTE 0 IN.

标签: pythonpostgresqlpsycopg2

解决方案


您必须使用查询初始化游标cursor.execute()。然后,您可以使用与客户端游标相同的功能(等)fetchone()fetchall()

SQLMOVE命令由psycopg2中的scroll(value[, mode='relative'])实现。

简单示例(查询生成 10 行,整数从 1 到 10):

with conn.cursor(name="curname") as cursor:
    cursor.itersize = 100
    cursor.execute("select generate_series(1, 10)")
    
    print('first:', cursor.fetchone())
    cursor.scroll(9, mode='absolute')
    print('tenth:', cursor.fetchone())
    cursor.scroll(0, mode='absolute')
    print('first again:', cursor.fetchone())

输出:

first: (1,)
tenth: (10,)
first again: (1,)

阅读有关服务器端游标的更多信息。


推荐阅读