Bogdan Kobylynskyi
Bogdan Kobylynskyi

Reputation: 1220

Java PreparedStatement set interval

What is the correct escaping of the interval in sql statement?

Currently I have the following code which escapes the customerId variable:

final String query = "delete from login_history where time < current_timestamp - '" + days + " days'::interval and customer_id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, customerId);
int deleted = preparedStatement.executeUpdate();

But I also want to escape days.

Upvotes: 0

Views: 2925

Answers (3)

Kirill
Kirill

Reputation: 41

You can use ?::interval in your SQL text and use setString() like

setString(1, "30 minutes")

Upvotes: 1

milosnkb
milosnkb

Reputation: 1591

The best solution is to 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

Upvotes: 1

Tim B
Tim B

Reputation: 41188

Replace "+ days +" with a ?, change the setInt to have 2 instead of 1 and add

preparedStatement.setWhateverTypeDaysIs(1, days);

Upvotes: 6

Related Questions