Search code examples
javajdbcnamed-parameters

Java named parameter's name (for Oracle JDBC function result)


I'm going to call a function, and set some parameters by name, example:

    Connection c = null;
    ResultSet rs = null;
    String query;
    PreparedStatement ps;
    CallableStatement cs = null;
    try {
        c = DbUtils.getConnection();
        cs = c.prepareCall("{? = call get_proc_name(?, ?) }");
        cs.registerOutParameter(1, OracleTypes.VARCHAR);
        cs.setInt("in_proc_type", ProcTypes.SELECT);
        cs.setLong("in_table_id", tableId);
        // here I should use something like cs.registerOutParameter("result", OracleTypes.VARCHAR);
        cs.execute();

PL/SQL function parameters are:

CREATE OR REPLACE FUNCTION get_proc_name
(
  in_proc_type IN NUMBER, /*1 - insert, 2 - update, 3 - delete, 4 - select*/
  in_table_name IN VARCHAR2 := NULL,
  in_table_id IN NUMBER := NULL,
  in_table_type_id IN NUMBER := NULL,
  is_new IN NUMBER := 0
) RETURN VARCHAR2

The question is how to register result as an out parameter, and then get it from oracle to java? I can register in/out parameters by name, because I know theirs names from function, but I don't know how go get function result, what variable name use for it.

Manuals describe only usage in/out params with procedures, not functions.

Oracle version: 11.1.0.6.0 Java version: 1.6.0_14


Solution

  • You register the function result as if it were the first parameter. Obviously, this shifts the numbering of the actual parameters.

    Your already existing line

    cs.registerOutParameter(1, OracleTypes.VARCHAR);
    

    is all it takes. After the call, get your result like this:

    String result = cs.getString(1);