在java語言中調用儲存函數

來源:互聯網
上載者:User
串連oracle資料庫private static Connection conn;static{//第一步:載入驅動try {Class.forName("oracle.jdbc.driver.OracleDriver");//得到連線物件conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","scott");} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}執行個體一:【create or replace function sumSal(emp_no number)--function(參數的值  必須有類型)--傳回值類型return number--必須有傳回值as--聲明變數emp_sal emp.sal%type;emp_comm emp.comm%type;total emp.sal%type;begin  select sal,comm into emp_sal,emp_comm from emp where empno=emp_no;  total:=emp_sal*12+nvl(emp_comm,0);  return total;--必須返回  傳回值類型一定相同end;】public static void functionTest1() throws SQLException{//mypackage 儲存函數CallableStatement cas=conn.prepareCall("{?=call sumSal(?)}");//從1開始int index = 1;cas.registerOutParameter(index++, oracle.jdbc.OracleTypes.NUMBER);//為預留位置賦值cas.setInt(index++,7369);boolean flag=cas.execute();System.out.println(flag);System.out.println(cas.getInt(1));}執行個體二:【通過包結構建立儲存函數create or replace package mypackage is  type empc1 is ref cursor;  function queryEmps return empc1;end mypackage;包體create or replace package body mypackage isfunction queryEmps return empc1 is  emp_c1 empc1;  begin    open emp_c1 for select * from emp;    return emp_c1;  end;  end mypackage;】public static void functionTest2() throws SQLException{//mypackage 儲存函數CallableStatement cas=conn.prepareCall("{?=call mypackage.queryEmps}");//從1開始int index = 1;cas.registerOutParameter(index++, oracle.jdbc.OracleTypes.CURSOR);boolean flag=cas.execute();System.out.println(flag);//調用裡邊的getCursor方法 返回的是ResultSet結果集ResultSet rs = ((OracleCallableStatement)cas).getCursor(1);while(rs.next()){System.out.println(rs.getInt(1));}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.