java 調用 oracle 預存程序

來源:互聯網
上載者:User

標籤:style   http   io   ar   color   os   sp   for   java   

-- 編寫過程,要求輸入僱員編號,返回僱員姓名。
create or replace procedure getNameByNo(no in number, name out varchar2) is
begin
  select ename into name from emp where empno = no;
end;
 
-- 輸入部門號,返回該部門所有員工
-- 先建一個包,定義一個遊標類型
create or replace package pkg_cursor is
  type my_cursor_type is ref cursor;
end pkg_cursor;
 
-- 建立過程
create or replace procedure getByDeptno(depno in number, emp_cursor out pkg_cursor.my_cursor_type) is
begin
  open emp_cursor for
  select * from emp where deptno = depno;

end;


2) java中調用的過程

a. 註冊驅動類,並擷取資料庫連接

b. 用程序呼叫SQL語句(用{}括起來)擷取CallableStatement對象。

c. 設定輸入參數,如:cs.setInt(1, 7788);

d. 註冊輸出參數,如:cs.registerOutParameter(2, oracle.jdbc.OracleTypes.VARCHAR);

e. 執行過程cs.execute();

f. 擷取過程返回結果,如:ResultSet rs = (ResultSet)cs.getObject(2);

 

g. 最後在finally中關閉資源

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;




public class TestPro1 {
static final int empno = 7788;
static final int depno = 10;
public static void main(String[] args) {
Connection con = null;
CallableStatement cs = null;

try {
//註冊JDBC驅動類
Class.forName("oracle.jdbc.driver.OracleDriver");
//擷取串連
con = DriverManager.
getConnection("jdbc:oracle:thin: @localhost :1521:orcltest", "test", "mm");
/************************* getNameByNo start ****************************/
cs = con.prepareCall("{call getNameByNo(?,?)}");
//設定參數
cs.setInt(1, empno);
//註冊輸出參數
cs.registerOutParameter(2, oracle.jdbc.OracleTypes.VARCHAR);
//執行過程
cs.execute();

//擷取結果
String ename = cs.getString(2);
System.out.println("編號為" + empno + " 的姓名為:" + ename);
//編號為7788 的姓名為:SCOTT
/************************* getNameByNo  end  ****************************/

/************************* getByDeptno start ****************************/
cs = con.prepareCall("{call getByDeptno(?, ?)}");
//設定參數
cs.setInt(1, depno);
//註冊輸出參數
cs.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);
cs.execute();
//得到結果集
ResultSet rs = (ResultSet)cs.getObject(2);
System.out.println("部門號為" + depno + "的所有員工如下:");
while(rs.next()) {
System.out.println("員工編號:" + rs.getInt(1) + 
", 員工姓名:" + rs.getString(2));
}
/************************* getByDeptno  end  ****************************/
//關閉資源(應在finally, 由於是樣本就在這裡關了)
cs.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}


}

java 調用 oracle 預存程序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.