=========说明该案例使用的表是oracle数据库自带的emp表==========
--1、创建一个包
--包名是testpackage,
--包中定义了一种类型test_cursor,该类型是游标类型
create or replace package testpackage as
type test_cursor is ref cursor;
end testpackage;
--2、建存储过程。
create or replace procedure sp_pro10
(spNo in number,p_cursor out testpackage.test_cursor) is
begin
open p_cursor for select * from emp where deptno=spNo;
end;
--3、在java代码中调用
package test;
import java.sql.*;
public class TestOracle{
//定义Connection对象
public static Connection conn = null;
//定义CallableStatement对象
public static CallableStatement cs = null;
//定义返回的结果集对象
public static ResultSet rs = null;
public static void main(String[] args){
try{
//1、加载Oracle驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//2、取得数据库连接
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL","scott","tiger");
//3、实例化CallableStatement对象
cs = conn.prepareCall("{call sp_pro10(?,?)}");
//4、给?赋值
cs.setInt(1,10);
//5、给第二个?赋值
cs.registerOutParameter(2,oracle.jdbc.OracleTypes.CURSOR);
//7、执行
cs.execute();
//8、获取返回的值,注意返回值是第二个,此处必须写2
ResultSet rs = (ResultSet)cs.getObject(2);
//9、打印输出取得的值
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(rs!=null){
rs.close();
rs = null;
}
}catch(Exception e0){
e0.printStackTrace();
}finally{
try{
if(cs!=null){
cs.close();
cs = null;
}
}catch(Exception e1){
e1.printStackTrace();
}finally{
try{
if(conn!=null){
conn.close();
conn = null;
}
}catch(Exception e2){
e2.printStackTrace();
}
}
}
}
}
}