Getting error when using prepareStatement with interval in query

僤鯓⒐⒋嵵緔 提交于 2019-12-29 08:44:08

问题


When running this query SELECT SYSDATE + INTERVAL '7' DAY FROM DUAL; in a prepareStatement like this

    PreparedStatement ps =  connection.prepareStatement("select sysdate + interval ? day from dual" );      
    ps.setString(1, "7");
    ps.executeQuery();

It will throw an exception, that the syntax is not good, it clearly is, cuz i'm able to run the same query in sql-developer.

Is this a bug in PreparedStatement ? can i use prepared statements together with interval?


回答1:


The entire expression INTERVAL '7' DAY is a literal, you cannot simply replace a part of it with a variable (parameter). Use the function NUMTODSINTERVAL(?,'DAY') instead.




回答2:


PreparedStatement doesn't work with interval literals, so neither setInt nor setString works! http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements003.htm

For that reason if you want to dynamically change the days in your query (with interval literals), the only way is to concatenate that value.

In your example:

int yourDays = 7;
String query ="select sysdate + interval '" + yourDays + "' day from dual ";

Then you can use PreparedStatement if you need to add other parameters and to execute the query.




回答3:


It will work if you pass an int parameter multiplied by a fixed interval E.g.

select * from foo where (time + ? * INTERVAL '1' DAY) > current_timestamp

You can put days, hours whatever... and than setInt parameter



来源:https://stackoverflow.com/questions/29066015/getting-error-when-using-preparestatement-with-interval-in-query

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