java接受oracle存儲過程返回的結果集(案例版)

需求java

1)函數部分sql

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)oop

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中測試fetch

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來調用存儲過程返回結果集   spa

 調用存儲過程時,要用CallabelStatement的prepareCall 方法。結構:{call 存儲過程名(?,?,...)}在設置參數的時候,輸入參數用set,輸出參數要registerOutParameter。取出輸出參數的值能夠直接用CallabelStatement的get方法.net

@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);         }         }
相關文章
相關標籤/搜索