Search code examples
javapostgresqlprepared-statement

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.


Solution

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

    preparedStatement.setWhateverTypeDaysIs(1, days);