如何从JDBC Callablestatement访问此存储过程?

时间:2011-07-24 03:07:39

标签: jdbc

如何从JDBC Callablestatement访问此存储过程?

public class TestOCIApp {

public static void main(String args[]) throws ClassNotFoundException,
SQLException {

try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcle", "scott", "tiger");

CallableStatement cs = conn.prepareCall("{call test(?,?)}");
cs.setInt(1, 10);

cs.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);

ResultSet rs = (ResultSet)cs.getObject(2);

while(rs.next())
{
System.out.println(rs.getString(2));
}

conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

我的异常是

java.sql.SQLException:列索引无效 * at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180)* * at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:222)* * at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:285)* * at oracle.jdbc.driver.OracleStatement.prepare_for_new_get(OracleStatement.java:2804)* * at oracle.jdbc.driver.OracleStatement.getObjectValue(OracleStatement.java:4983)* * at oracle.jdbc.driver.OracleStatement.getObjectValue(OracleStatement.java:4964)* * at oracle.jdbc.driver.OracleCallableStatement.getObject(OracleCallableStatement.java:586)* *在TestOCIApp.main(TestOCIApp.java:23)*

create or replace procedure test( p_deptno IN number
, p_cursor OUT SYS_REFCURSOR)
is
begin
open p_cursor FOR
select *
from emp
where deptno = p_deptno;
end test;
/

1 个答案:

答案 0 :(得分:4)

当与oracle游标交易时,CallableStatement对象被强制转换为OracleCallableStatement以使用getCursor方法,该方法是标准JDBC应用程序编程接口(API)的Oracle扩展,并将REF CURSOR返回到ResultSet对象。

cstmt.registerOutParameter(1, OracleTypes.CURSOR);
cstmt.execute();
cursor = ((OracleCallableStatement)cstmt).getCursor(1);

while (cursor.next ()){
System.out.println (cursor.getString(1));
} 

但是这会将你的代码耦合到oracle数据库[:(]