用光标来作为out参数的作用,当遇到要输出某条记录的一整行,或者要输出多条记录时。
使用光标来作为存储过程的out参数,其格式和不同于单纯的用其他类型作为out参数的存储过程。
创建一个包
--查询某个部门中所有员工的所有信息 CREATE OR REPLACE PACKAGE MYPACKAGE AS type empcursor is ref cursor; procedure queryEmpList(dno in number,empList out empcursor); END MYPACKAGE;
实现包体
CREATE OR REPLACE PACKAGE BODY MYPACKAGE AS procedure queryEmpList(dno in number,empList out empcursor) AS BEGIN open empList for select * from emp where deptno=dno; END queryEmpList; END MYPACKAGE;
调用该存储过程的java代码
在调用前确保包已经在orcale数据库中申明好了
@Test public void testCursorPro() throws SQLException{ Connection conn = JDBCUtils.getConnection(); CallableStatement calls = conn.prepareCall("{call mypackage.queryEmpList(?,?)}"); calls.setInt(1, 7369); calls.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR); calls.execute(); //必须将callableStatement强转为OracleCallableStatement,才能得到游标类型的out值 OracleCallableStatement oraCalls = (OracleCallableStatement)calls; //该方法返回一个ResultSet结果集 ResultSet rs = oraCalls.getCursor(2); while(rs.next()){ System.out.println(rs.getInt(1) + " " + rs.getString(2)); } }