项目中经常会用到模糊查询,最近使用JdbcTemplate过程中就遇到了。
一开始尝试了拼接的方式去
String sql = "select count(1) from web_users where status = ? and " + "createtime >= ? and createtime <= ? and deleted = 0 and " + "address like '%"+"?"+"%'"; return getJdbcTemplate().queryForObject(sql, new Object[]{status, new Timestamp(begintime), new Timestamp(endtime), address}, Integer.class);
或
String sql = "select * from web_users where status = ? and " + "createtime >= ? and createtime <= ? and deleted = 0 and " + "address like ? limit ? offset ?"; return getJdbcTemplate().query(sql, new Object[]{status, new Timestamp(begintime), new Timestamp(endtime), "'%"+address+"'%", count, start}, new DaoRowMapper<>(User.class));
以上两种方式都会报同样的错误。参数不正确。
既然这两种方式通不行,尝试以下方式:
List<Object> queryList = new ArrayList<>(); if (!address.equals("")) { sql += " and address like ? "; queryList.add("%" + address + "%"); } return getJdbcTemplate().query(sql, queryList.toArray(), new DaoRowMapper<>(User.class));
哈哈哈,搞定!