標籤:nec pos creat ack .exe 準備 cal into out
一、環境準備
登入Oracle資料庫scott帳號,利用emp進行操作。
1、建立 proc_getyearsal 預存程序
1 -- 擷取指定員工年薪2 create or replace procedure proc_getyearsal(vempno in number,vyearsal out number)3 is4 5 begin6 select sal*12+nvl(comm,0) into vyearsal from emp where empno=vempno;7 end;
2、建立 proc_gettemps 預存程序(遊標)
1 create or replace procedure proc_gettemps(vemps out sys_refcursor)2 is3 BEGIN4 open vemps for select * from emp where deptno = 20;5 end;
3、匯入資料庫驅動包 —— ojdbc14.jar
二、java程式碼範例
1 package com.pri.test; 2 3 public class TestProcedure { 4 5 /* 6 java調用預存程序模板(一) 7 擷取單值操作 8 */ 9 @Test10 public void test01() throws Exception {11 //1.註冊驅動12 Class.forName("oracle.jdbc.driver.OracleDriver");13 //2.擷取串連14 String url = "jdbc:oracle:thin:@10.211.55.29:1521/orcl";15 String user = "zhangsan";16 String password = "zs123";17 Connection conn = DriverManager.getConnection(url, user, password);18 //3.擷取執行SQL的對象19 String sql = "{call proc_getyearsal(?,?)}";20 CallableStatement callableStatement = conn.prepareCall(sql);21 //3.1 設定輸出參數22 callableStatement.setInt(1,7369);23 //3.2 註冊輸出類型24 callableStatement.registerOutParameter(2, Types.DOUBLE);25 //4.執行SQL26 callableStatement.execute();27 //5.執行結果28 double yearsal = callableStatement.getDouble(2);29 System.out.println("年薪:"+yearsal);30 //6.釋放資源31 callableStatement.close();32 conn.close();33 }34 35 /*36 java調用預存程序模板(二)37 多行記錄(遊標)操作38 */39 @Test40 public void test03() throws Exception {41 //1.註冊驅動42 Class.forName("oracle.jdbc.driver.OracleDriver");43 //2.擷取串連44 String url = "jdbc:oracle:thin:@10.211.55.29:1521/orcl";45 String user = "zhangsan";46 String password = "zs123";47 Connection conn = DriverManager.getConnection(url, user, password);48 //3.擷取執行SQL的對象49 String sql = "{call proc_gettemps(?)}";50 CallableStatement callableStatement = conn.prepareCall(sql);51 //3.1 註冊輸出類型52 callableStatement.registerOutParameter(1, OracleTypes.CURSOR);53 //4.執行SQL54 callableStatement.execute();55 //5.擷取結果56 System.out.println(callableStatement.getClass().getName());57 // T4CCallableStatent call2 = () callableStatement;58 OracleCallableStatement call2 = (OracleCallableStatement) callableStatement;59 ResultSet rs = call2.getCursor(1);60 61 while(rs.next()){62 System.out.println(rs.getObject("empno"));63 System.out.println(rs.getObject("ename"));64 System.out.println(rs.getObject("sal"));65 System.out.println("------------------------");66 }67 //6.釋放資源68 rs.close();69 callableStatement.close();70 conn.close();71 }72 73 }
Oracle資料庫基本操作 (五) —— 使用java調用預存程序