在Java语言中调用存储函数


连接Oracle数据库 

  1. private static Connection conn;  
  2.     static{  
  3.         //第一步:加载驱动  
  4.             try {  
  5.                 Class.forName("oracle.jdbc.driver.OracleDriver");  
  6.                 //得到连接对象        conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","scott");  
  7.             } catch (ClassNotFoundException e) {  
  8.                 // TODO Auto-generated catch block  
  9.                 e.printStackTrace();  
  10.             } catch (SQLException e) {  
  11.                 // TODO Auto-generated catch block  
  12.                 e.printStackTrace();  
  13.             }  
  14.     }  

实例一: 

  1. 【  
  2. create or replace function sumSal(emp_no number)--function(参数的值  必须有类型)   
  3. --返回值类型   
  4. return number--必须有返回值   
  5. as  
  6. --声明变量   
  7. emp_sal emp.sal%type;  
  8. emp_comm emp.comm%type;  
  9. total emp.sal%type;  
  10. begin  
  11.   select sal,comm into emp_sal,emp_comm from emp where empno=emp_no;  
  12.   total:=emp_sal*12+nvl(emp_comm,0);  
  13.   return total;--必须返回  返回值类型一定相同   
  14. end;  
  15. 】  
  16. public static void functionTest1() throws SQLException{  
  17.         //mypackage 存储函数  
  18.         CallableStatement cas=conn.prepareCall("{?=call sumSal(?)}");  
  19.         //从1开始  
  20.         int index = 1;  
  21.         cas.registerOutParameter(index++, oracle.jdbc.OracleTypes.NUMBER);  
  22.         //为占位符赋值  
  23.         cas.setInt(index++,7369);  
  24.         boolean flag=cas.execute();  
  25.         System.out.println(flag);  
  26.         System.out.println(cas.getInt(1));  
  27.     }  
  • 1
  • 2
  • 下一页

相关内容