简体   繁体   中英

JDBC template giving error for Query using “like”

I am not getting how to use %?% in the query below. It's giving me error:

PreparedStatementCallback; uncategorized SQLException for SQL [select * from names where name like '%?%']

Problem:

String sql = "select * from names where name like ?";
List<NamesModel> names = jdbcTemplate.query(sql, new Object[]{searchName}, new NamesRowMapper());

Your exception tells you that you can't bind into quoted value. Below won't work:

String sql = "select * from names where name like '%?%'";
List<NamesModel> names = jdbcTemplate.query(sql, 
        new Object[]{ searchName }, new NamesRowMapper());

The correct way is to add % around searchName parameter value:

String sql = "select * from names where name like ?";
List<NamesModel> names = jdbcTemplate.query(sql, 
        new Object[]{ "%" + searchName + "%"}, new NamesRowMapper());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM