Oracle JDBC从过程获取SYS_REFCURSOR

时间:2018-11-29 02:56:11

标签: java oracle jdbc sys-refcursor

我正在使用Oracle 12g,并试图从ResultSet中获取SYS_REFCURSOR

我有一个带有以下签名的过程:

CREATE OR REPLACE PROCEDURE proc_search(user IN VARCHAR2, res OUT SYS_REFCURSOR)

这是我正在使用的Java JDBC代码:

try {
    CallableStatement cstmt = con.prepareCall("exec proc_search(?, ?)");
    cstmt.setString(1, login);
    cstmt.registerOutParameter(2, Types.REF);
    cstmt.execute();
    ResultSet rs = (ResultSet)cstmt.getObject(2);

    while (rs.next()) {
        System.out.println(rs.getString(1));
    }
} catch (Exception e) {
    System.err.println(e);
    e.printStackTrace();
}

但是,出现以下错误:

  

java.sql.SQLException:ORA-03115:不支持的网络数据类型或表示形式

1 个答案:

答案 0 :(得分:2)

首先,getCursor应该使用SYS_REFCURSOR方法而不是getObject

第二,prepareCall应该有BEGINEND

代码段

try {
    CallableStatement cstmt = con.prepareCall("BEGIN proc_search(?, ?); END;");
    cstmt.setString(1, login);
    cstmt.registerOutParameter(2, OracleTypes.CURSOR); 
    cstmt.execute();
    ResultSet rs = ((OracleCallableStatement)cstmt).getCursor(2);

    while (rs.next()) {
        System.out.println(rs.getString("name"));
    }
} catch (Exception e) {
    System.err.println(e);
    e.printStackTrace();
}

请注意,必须有一个finally块来关闭Connection,CallableStatement,ResultSet等。

finally {
    try {
        if (con != null)
            con.close();

        if (cstmt!= null)
            cstmt.close();

        if (rs!= null)
            rs.close();

    } catch (SQLException sqlexc) {
        sqlexc.printStackTrace();
    }
}

更新1

使用CallableStatement

    Connection conn = null;
    CallableStatement callableStatement = null;
    ResultSet rs = null;

    try {
        conn = getconn();
        callableStatement = conn.prepareCall("{call proc_search(?, ?)}");    
        callableStatement.setString(1, login);
        callableStatement.registerOutParameter(2, OracleTypes.CURSOR);

        callableStatement.executeUpdate();    

        rs = (ResultSet) callableStatement.getObject(2);    
        while (rs.next()) {
            String userid = rs.getString("name");
        }

    } catch (SQLException e) {

        System.out.println(e.getMessage());
        e.printStackTrace();

    } finally {

        if (rs != null) {
            rs.close();
        }

        if (callableStatement != null) {
            callableStatement.close();
        }

        if (conn != null) {
            conn.close();
        }

    }

    }