How to delete multiple rows with JdbcTemplate

Sunil Kumar Naik picture Sunil Kumar Naik · May 31, 2016 · Viewed 11.3k times · Source

Want to delete multiple rows with the help of JdbcTemplate. In the below code msgNos is a String variable containing comma separated value like 26,27. After executing the statements it is only deleting one record.

String sqlQuery = " delete from canned_message where msg_no in (?)";
Object[] params = {msgNos};
int rows = smsdbJdbcTemplate.update(sqlQuery, params);

Answer

Karthikeyan Vaithilingam picture Karthikeyan Vaithilingam · May 31, 2016

Instead of org.springframework.jdbc.core.JdbcTemplate use org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate where you can use named parameter.

Then in your query you can pass List as parameter value in the in clause

String sqlQuery = "delete from canned_message where msg_no in (:msgNos)";
List<Integer> params = <array list of number>;
Map namedParameters = Collections.singletonMap("msgNos", params);
int rows = smsdbJdbcTemplate.update(sqlQuery, namedParameters);

Note: I've used List<Integer> use appropriate datatype as you need.