简体   繁体   中英

Prepared statement with date added by interval as parameter in Postgresql

This works:

String query = "select DATE '2016-03-16' + interval '7 days'";

But I want to have '2016-03-16' and 7 as parameters in a prepared statement. How to do it?

I tried like this, but it didn't work:

String query = "select DATE ? + interval ?";
Object param[] = {"2016-03-16", "7 days"};

Try something like:

select to_date(?, 'YYYY-MM-DD') + cast(? as interval)

Other option is to use something like

select cast(? as date) + cast(? as interval)

but it depends on current locale for date conversion

If using Java i'd say the cleanest approach would be to use org.postgresql.util.PGInterval

Set your query as follows (don't mention 'interval'):

String query = "select DATE ? + ?";

And add your prepared statement values in this way:

stmt.setDate(1, java.sql.Date.valueOf("2016-03-16"));
stmt.setObject(2, new PGInterval(0, 0, 7, 0, 0, 0));

In effect, using PGInterval represents the whole of interval '7 days'

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