java接受oracle存储过程返回的结果集(案例版)

需求

1)函数部分

create or replace function f_dept_money_min
return number
is
 v_min number;
begin
  select min(money) into v_min from biao;
  return v_min;
end;

2)存储过程部分

sys_refcursor,可以在存储过程中作为参数返回一个table格式的结构集(我把他认为是table类型,容易理解,其实是一个游标集), cursor 只能用在存储过程,函数,包等的实现体中,不能做参数使用。sys_refcursor 这东西可以使用在包中做参数,进行数据库面向对象开放

create or replace procedure pro_money(out_return out sys_refcursor)

is
begin
  --将最低工资提高200
   for tab in (
  select id from biao where money=f_dept_money_min())
  loop
    update biao set money=money+200 where id=tab.id;
    end loop;
  --将最低工资提高100
  for tab1 in(
    select id from biao where money>f_dept_money_min()+200
    and money<f_dept_money_min()+400
    )
    loop
    update biao set money=money+200 where id=tab1.id;
    end loop;
    commit;
   --返回列表编号,姓名,工资
   open out_return for 'select id,name,money from biao';
end;

3)plsql中测试

declare
  cur1   SYS_REFCURSOR;
  i      biao%rowtype;
begin
 sql_test(cur1);
  loop
    fetch cur1
      into i;
    exit when cur1%notfound;
    dbms_output.put_line('----------------:' || i.id||i.name||i.money);--id为表baio中的id列
  end loop;
  close cur1;
end;

4)用jdbc来调用存储过程返回结果集   

 调用存储过程时,要用CallabelStatement的prepareCall 方法。结构:{call 存储过程名(?,?,...)}在设置参数的时候,输入参数用set,输出参数要registerOutParameter。取出输出参数的值可以直接用CallabelStatement的get方法

@Test
    public void proMoney(){
        java.sql.Connection conn=null;
        java.sql.CallableStatement stmt=null;
        ResultSet rs=null;
        try {
            conn=DaoUtil.getConnection();
            stmt=conn.prepareCall("{call pro_money(?)}");
            stmt.registerOutParameter(1, OracleTypes.CURSOR);
            stmt.execute();            
            rs = (ResultSet) stmt.getObject(1);
            while(rs.next()){
            String name = rs.getString("name");
            double ids = rs.getDouble("id");
            int money = rs.getInt("money");
            System.out.println("name="+name+"ids="+ids+"money="+money);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DaoUtil.closeAll(rs, stmt, conn);
        }    
    }

猜你喜欢

转载自my.oschina.net/u/585635/blog/910811