Oracle数据库基本操作 (五) —— 使用java调用存储过程

时间:2023-03-08 20:29:29

一、环境准备

 登录Oracle数据库scott账号,利用emp进行操作。

1、创建 proc_getyearsal 存储过程

 -- 获取指定员工年薪
create or replace procedure proc_getyearsal(vempno in number,vyearsal out number)
is begin
select sal*12+nvl(comm,0) into vyearsal from emp where empno=vempno;
end;

2、创建 proc_gettemps 存储过程(游标)

 create or replace procedure proc_gettemps(vemps out sys_refcursor)
is
BEGIN
open vemps for select * from emp where deptno = 20;
end;

3、导入数据库驱动包 —— ojdbc14.jar

二、java代码示例

 package com.pri.test;

 public class TestProcedure {

   /*
    java调用存储过程模板(一)
    获取单值操作
  */
@Test
public void test01() throws Exception {
//1.注册驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//2.获取连接
String url = "jdbc:oracle:thin:@10.211.55.29:1521/orcl";
String user = "zhangsan";
String password = "zs123";
Connection conn = DriverManager.getConnection(url, user, password);
//3.获取执行SQL的对象
String sql = "{call proc_getyearsal(?,?)}";
CallableStatement callableStatement = conn.prepareCall(sql);
//3.1 设置输出参数
callableStatement.setInt(1,7369);
//3.2 注册输出类型
callableStatement.registerOutParameter(2, Types.DOUBLE);
//4.执行SQL
callableStatement.execute();
//5.执行结果
double yearsal = callableStatement.getDouble(2);
System.out.println("年薪:"+yearsal);
//6.释放资源
callableStatement.close();
conn.close();
}
  
  /*
   java调用存储过程模板(二)
    多行记录(游标)操作
  */
@Test
public void test03() throws Exception {
//1.注册驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//2.获取连接
String url = "jdbc:oracle:thin:@10.211.55.29:1521/orcl";
String user = "zhangsan";
String password = "zs123";
Connection conn = DriverManager.getConnection(url, user, password);
//3.获取执行SQL的对象
String sql = "{call proc_gettemps(?)}";
CallableStatement callableStatement = conn.prepareCall(sql);
//3.1 注册输出类型
callableStatement.registerOutParameter(1, OracleTypes.CURSOR);
//4.执行SQL
callableStatement.execute();
//5.获取结果
System.out.println(callableStatement.getClass().getName());
// T4CCallableStatent call2 = () callableStatement;
OracleCallableStatement call2 = (OracleCallableStatement) callableStatement;
ResultSet rs = call2.getCursor(1); while(rs.next()){
System.out.println(rs.getObject("empno"));
System.out.println(rs.getObject("ename"));
System.out.println(rs.getObject("sal"));
System.out.println("------------------------");
}
//6.释放资源
rs.close();
callableStatement.close();
conn.close();
} }