使用JDBC调用Oracle包的详解

1.Oracle的包头

--【包头】
create or replace package A_package1 is

  --在此处输入程序包声明(类型,异常错误,方法等)
  type classCursor is ref cursor;
  --定义存储过程使用游标
  procedure findClassInfoById(v_worktype in varchar2,v_classinfo out classCursor);
end A_package1;

 

2.Oracle的包体

--【包体】
create or replace package body A_package1 is
       procedure findClassInfoById(v_classid in varchar2,v_classinfo  out classCursor) as
       begin
                 --根据指定的部门编号查询多个员工信息赋值给输出型变量的游标
                 open v_classinfo for select * from classinfo where worktype=v_worktype;
       end findClassInfoById;
end A_package1;

 

3.JDBC调用Oracle包的Java代码

package cn.itcast.packages;

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

import oracle.jdbc.OracleCallableStatement;

/**
 * 通过JDBC调用包*/
public class Main {
	
	public static void main(String[] args) throws Exception{
		
		//声明变量
		//驱动地址
		String driverClass="oracle.jdbc.OracleDriver"; 
		//连接地址
		String url="jdbc:oracle:thin:@localhost:1521:orcl";
		//帐号
		String username="SCOTT";
		//密码
		String psw="Root123";
		
		//加载驱动
		Class.forName(driverClass);
		
		//获取连接对象
		Connection conn=DriverManager.getConnection(url,username,psw);
		
		
		//创建执行存储过程的语句对象(这里应该是包的语句对象)
		String sql="{call A_package1.findClassInfoById(?,?)}";
		CallableStatement call=conn.prepareCall(sql);
		
		//设置参数类型
		call.setString(1, "经理");
		call.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);
		
		//执行
		call.execute();
		
		//获取值
		ResultSet set=((OracleCallableStatement)call).getCursor(2);
		
		//遍历
		while(set.next()){
			String classid=set.getString(1);
			String classname=set.getString(2);
			String salary=set.getString(5);
			String comm=set.getString(7);
			String worktype=set.getString(6);
			
			System.out.println("编号:"+classid+",姓名:"+classname+",职位:"+worktype+",工资:"+salary+",奖金:"+comm);
			
		}
		
		//释放资源
		set.close();
		conn.close();
		call.close();
		
	}

}

 

你可能感兴趣的:(Oracle)