Search code examples
javajpastored-proceduresjdbcjava-stored-procedures

How to set parameter by name instead of its position in JDBC/JPA when calling stored procedure?


I'm calling stored procedure from java. Now I need to set the stored procedure's parameter by its name instead of its position inidex, is it doable?

I don't want to use string concatenation though, it's not safe and ugly to deal with.

Notice: I need to work with OUT/INOUT parameters, too.


Solution

  • We can name the parameters using the format

    cstmt.setString("arg", name);
    

    where cstmt is an CallableStatement

    where arg is the name of the argument in the corresponding stored procedure.

    We do not need to name parameters in the same order as the arguments in the stored procedure as we will use paramname in this case.

    Also you can go through the Tutorial regarding the CallableStatement in the below link -

    http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.jdbc_pg.doc/jdbc89.htm

    You can read the link - the registerOutParameter statement is there in the link -

    // Register out parameter which should return the product is created.
      cstmt.registerOutParameter("prod_id", Types.FLOAT);