如何将SQL字符串值作为PreparedStatement的参数传递给DB2的cast()函数作为时间戳?

问题描述 投票:0回答:1

如果我在 DBeaver for IBM DB2 LUX 数据库中执行以下查询,一切都会很好。

 UPDATE PERSON SET entry_time = case   
     when ucase('CURRENT') = 'CURRENT' then current timestamp  
     when 'CURRENT' <= '' then current timestamp  
     else cast('CURRENT' as timestamp)  
     END 
    WHERE person_id ='1'

我稍微更改了查询以使用

PreparedStatement
执行它。这是
PreparedStatement
的删减。

String current = "CURRENT";
String id = "1";

PreparedStatement pstmt = connection.prepareStatement( "UPDATE PERSON SET entry_time = case   
     when ucase(?) = 'CURRENT' then current timestamp  
     when ? <= '' then current timestamp  
     else cast(? as timestamp)  
     END 
    WHERE person_id = ?");

pstmt.setString(1,current);
pstmt.setString(2,current);
pstmt.setString(3,current);
pstmt.setString(4,id);

当我在没有任何框架的情况下使用直接 JDBC 连接对 DB2 执行此查询时,出现以下异常。我不知道为什么,但服务器尝试先执行

cast(? as timestamp)  
部分,在执行过程中不会到达该部分,然后失败。

数据转换无效:参数实例 CURRENT 对于请求的到 java.sql.Timestamp 的转换无效。

我试图了解如何检索执行计划,但到目前为止我还没有成功。

有什么想法吗?

我尝试使用 IBM DB2 JCC

preparedStatement (com.ibm.db2.jcc.DB2PreparedStatement)
尝试另一种方法,但没有成功。

java sql jdbc db2 sql-timestamp
1个回答
0
投票

您尝试准备一个带有字符串参数的语句,其值为

"CURRENT"
。该值是一个 Java 字符串,而不是查询编辑器中使用的 SQL 字符串。要将 SQL 字符串传递给 DB,您需要用引号将其括起来,以便 DB 将其识别为字符串。然后,当查询执行为
cast()
时,您可以应用
timestamp
函数。

String current = "'CURRENT'";
String id = "'1'";
© www.soinside.com 2019 - 2024. All rights reserved.