java如何调用存储过程这里不再详述,本文主要介绍java如何获取cursor的值。
本来也不是什么困难的程序,但是本人整整研究了俩天才得到自己想要的结果,在调试的时候从网上也查了很多资料,但为什么总是出错呐,今天才知道是什么原因。就是system账号的原因,我在调试的时候是用的system用户DBA角色登陆的,在该用户下不知道为什么调用存储过程总是没有结果,要是换成创建的其他用户就会得到自己想要的结果,这个问题现在先遗留下。
下面正式开始编程:
首先,建立存储过程( 建立student表略):
create or replace procedure p_student_info(i_sex invarchar2,o_cur out sys_refcursor) is begin open o_cur for select * from student wherestudent_sex=i_sex; end;
存储过程既有in类型也有out类型且out类型是cursor。
java代码:
建立数据库链接省略,注意不要以system账号链接:
调用方法:
public static void cursorTest(){ Connection conn =JdbcUtil.getConnection(); CallableStatement cstmt =null; try { cstmt =conn.prepareCall("{call p_student_info(?,?)}"); cstmt.setString(1,"m"); cstmt.registerOutParameter(2,OracleTypes.CURSOR);//out类型需要注册 cstmt.execute(); ResultSet rs= (ResultSet)cstmt.getObject(2);//此处的2要与存储过程中cursor的问题对应 while(rs.next()){ System.out.println(rs.getString(1));//获取具体的值 } } catch (SQLException e){ // TODOAuto-generated catch block e.printStackTrace(); }finally{ try { if(rs!= null) rs.close(); if(cstmt!= null) cstmt.close(); if(conn!= null){ conn.close(); } } catch(SQLException e) { //TODO Auto-generated catch block e.printStackTrace(); } } }
调用以上方法测试。