1

I'm dealing with a situation where I use parameters in a PreparedStatement multiple times:

SELECT * FROM SOME_TABLE
WHERE (A LIKE 'searchterm1' OR B LIKE 'searchterm1' OR C LIKE 'searchterm1')
AND   (A LIKE 'searchterm2' OR B LIKE 'searchterm2' OR C LIKE 'searchterm2')

When filling the parameters, I have to supply each parameter (searchterm1 and searchterm2) multiple times:

try (PreparedStatement statement = connection.prepareStatement(
        "SELECT * FROM SOME_TABLE " +
                " WHERE (A LIKE ? OR B LIKE ? OR C LIKE ?) " +
                " AND   (A LIKE ? OR B LIKE ? OR C LIKE ?")) {
    statement.setString(1, "searchterm1");
    statement.setString(2, "searchterm1");
    statement.setString(3, "searchterm1");
    statement.setString(4, "searchterm2");
    statement.setString(5, "searchterm2");
    statement.setString(6, "searchterm2");
    ResultSet resultSet = statement.executeQuery();
}

Is there a way to reference the same parameter multiple times in a prepared statement query, so I only need to set it once (per parameter)? So something like

  • Named parameters: :searchterm1, or
  • Indexed parameters: ?1
Peter Walser
  • 15,208
  • 4
  • 51
  • 78
  • The solution from the duplicate uses procedures, not sure if these are available to you – Lino Feb 28 '19 at 09:31
  • Maybe this helps you too: [Using SQL LIKE and IN together](https://stackoverflow.com/a/2318163/5515060) – Lino Feb 28 '19 at 09:33
  • The Spring `NamedParameterJdbcTemplate` in the reference question looks like a viable solution to me, thanks. – Peter Walser Feb 28 '19 at 09:55

0 Answers0