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

家住魔仙堡 提交于 2020-01-24 00:33:10

问题


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.


回答1:


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);



回答2:


It is feasible, however not natively within the language. You will need to write your own code to provide this functionality or rely upon a third parties code (recommended approach). I have used the simple code from this article in the past with success. It doesn't handle all cases but it is easily extendable. The SpringFramework also provides some libraries to provide this functionality if your looking for a more robust solution.



来源:https://stackoverflow.com/questions/15334931/how-to-set-parameter-by-name-instead-of-its-position-in-jdbc-jpa-when-calling-st

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!