问题3:
编写一个过程,输入部门号,返回该部门所有雇员信息。
分析:由于oracle存储过程是没有返回值的,它的所有返回值都是通过out参数来替代的,列表同样是如此,但由于是集合,所以不能用一般的参数,要用package
--1.创建一个包,在该包中,定义类型test_cursor,游标
create or replace package testpackage as
type test_cursor is ref cursor;
end testpackage;
--2.创建过程
create procedure sp_pro10(spNo in number,sp_cursor out testpackage.test_cursor) is
begin
open sp_cursor for select * from emp where deptno=spNo;
end;
--3.在java中调用过程
package com.sw;
import java.sql.*;
public class Test4 {
/*
* 无返回值的过程实例
*/
public static void main(String[] args) {
//变量
Connection conn = null;
CallableStatement cs = null;
try {
//声明驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//得到链接
conn = DriverManager
.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl",
"scott","Oracle1");
//创建CallableStatement,调用过程必须使用
cs = conn.prepareCall("{call sp_pro10(?,?)}");
//给?赋值
cs.setInt(1, 10);
//给其余的变量关联值
cs.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);
//执行
cs.execute();
//取出返回值
ResultSet rs = (ResultSet) cs.getObject(2);
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
} catch (Exception e) {
e.printStackTrace();
}finally{
//关闭资源
try {
cs.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}