Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete multiple rows with JdbcTemplate

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);
like image 446
Sunil Kumar Naik Avatar asked May 31 '16 07:05

Sunil Kumar Naik


People also ask

How do I delete multiple records in JDBC?

DELETE FROM table_name WHERE column_name BETWEEN value 1 AND value 2; Another way to delete multiple rows is to use the IN operator. DELETE FROM table_name WHERE column_name IN (value 1, value 2, value 3, etc...); If you want to delete all records from the table then you can use this syntax.

How do I select multiple columns in JdbcTemplate?

queryForList might be what you are looking for: List<Map<String, Object>> rows = jdbcTemplate. queryForList("SELECT name, middle, family FROM table"); Every Map in this List represents a row in the returned query, the key represents the column name, and the value is the value of that column for that row.

How does JdbcTemplate get single record?

Query for Single Row In Spring, we can use jdbcTemplate. queryForObject() to query a single row record from database, and convert the row into an object via row mapper. 1.2 Spring BeanPropertyRowMapper , this class saves you a lot of time for the mapping.


1 Answers

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.

like image 110
Karthikeyan Vaithilingam Avatar answered Sep 18 '22 19:09

Karthikeyan Vaithilingam