简体   繁体   中英

Getting error when using prepareStatement with interval in query

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?

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.

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.

It will work if you pass an int parameter multiplied by a fixed interval Eg

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM