暂无图片
当JDBC遇上返回Cursor
最近更新:2022-09-11 16:26:23

使用jdbc访问PostgreSQL或者MogDB(openGauss)数据库里的cursor游标时,官方文档可查的资料较少,下面的示例供参考。

测试环境

  • JDBC:postgresql-42.3.5.jar
  • PG: 14.2
  • MogDB(openGauss): 3.0.0

测试背景

针对function和procedure返回cursor游标类型,通过jdbc如何调用。

测试function:curtest1,通过returns返回游标类型

create or replace function curtest1() 
returns refcursor 
language plpgsql
as $function$ 
declare 
    cur refcursor;
begin 
    open cur for select id,data from fiverows;
    return cur;
end;
$function$;

测试procedure:curtest2,通过out参数返回游标类型

create or replace procedure curtest2(out cur refcursor) 
language plpgsql
as $procedure$ 
begin 
    open cur for select id,data from fiverows;
end;
$procedure$;

测试procedure:curtest3,通过out参数返回多个游标类型

create or replace procedure curtest3(out cur1 refcursor,out cur2 refcursor) 
language plpgsql
as $procedure$ 
begin 
    open cur1 for select id,data from fiverows where id between 1 and 3;
    open cur2 for select id,data from fiverows where id between 4 and 5;
end;
$procedure$;

表结构及数据

create table fiverows(id serial primary key,data text);
insert into fiverows(data) values('one'),('two'),
                       ('three'),('four'),('five');

测试一:function通过returns返回游标

......