Java调用用户定义的表函数DB2带有预准备语句

时间:2014-11-26 23:25:11

标签: java db2 prepared-statement user-defined-functions

我正在使用 Java 6 EE和DB2 开发一个Web应用程序。我创建了一个表函数,它接收3个参数并返回一个表。

CREATE FUNCTION MY_FUNCTION (PARAM1 VARCHAR(5), PARAM2 VARCHAR(10), PARAM3 INTEGER)
RETURNS TABLE (
    FIELD1 VARHCHAR(5),
    FIELD2 VARCHAR(10),
    FIELD3 INTEGER
)
RETURN 
SELECT FIELD1, FIELD2, FIELD3 
FROM TABLE_1 WHERE FIELD1 = PARAM1 || '_MAIN' 
AND FIELD2 = PARAM2 || '_MAIL' AND FIELD3 = PARAM3 + 47

我正在尝试用Java编写一个带有预处理语句的函数,如下所示(使用通配符):

PreparedStatement stmt = conn.prepareStatement("SELECT * FROM TABLE(MY_FUNCTION(?, ?, ?)) AS TABLE");

但是当我运行我的代码时,我在预准备语句中得到一个SQLSyntaxErrorException:

java.sql.SQLSyntaxErrorException: [SQL0418] A statement contains a use of a parameter marker that is not valid
       at com.ibm.as400.access.JDError.createSQLExceptionSubClass(JDError.java:828)
       at com.ibm.as400.access.JDError.throwSQLException(JDError.java:699)
       at com.ibm.as400.access.JDError.throwSQLException(JDError.java:669)
       at com.ibm.as400.access.AS400JDBCStatement.commonPrepare(AS400JDBCStatement.java:1660)
       at com.ibm.as400.access.AS400JDBCPreparedStatement.<init>(AS400JDBCPreparedStatement.java:248)
       at com.ibm.as400.access.AS400JDBCCallableStatement.<init>(AS400JDBCCallableStatement.java:120)
       at com.ibm.as400.access.AS400JDBCConnection.prepareCall(AS400JDBCConnection.java:1840)
       at com.ibm.as400.access.AS400JDBCConnection.prepareCall(AS400JDBCConnection.java:1741)

注意:如果我对这样的参数进行硬编码(没有wilcards)可以工作:

PreparedStatement stmt = conn.prepareStatement("SELECT * FROM TABLE(MY_FUNCTION('" + var1 + "', '" + var2 + "', '" + var3 + "')) AS TABLE");

我想要实现的是使用通配符调用函数来改进函数的处理

提前致谢

解决方案@ user384842回答

PreparedStatement stmt = conn.prepareStatement("SELECT * FROM TABLE(MY_FUNCTION(cast(? as VARCHAR(5)), cast(? as VARCHAR(10)), cast(? as INTEGER))) AS TABLE");

1 个答案:

答案 0 :(得分:3)

在Google上搜索了一下之后,看起来你可能需要将它们转换为合适的类型吗?我找到了这个文档:

requiresCastingOfParametersInSelectClause() 
DB2 in fact does require that parameters appearing in the select clause be wrapped in cast() calls to tell the DB parser the type of the select value.

这里: https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/dialect/DB2Dialect.html

不确定它是否相关,但可能值得一去?我猜它看起来像cast(? as varchar(30))

在此处投射链接http://www.dbatodba.com/db2/how-to-do/how-to-convert-data-types-on-db2/