项目场景:
mysql模糊查询乱码_Mybatis使用MySQL模糊查询时输入中文检索,接收到乱码报错
问题描述
mysql模糊查询乱码_Mybatis使用MySQL模糊查询时输入中文检索,接收到乱码报错
在 mapper.xml 文件中使用模糊查询,在mapper文件sql语句的条件位置加上%
<select id="selectStudentsLikeTwo" resultType="Student">
select * from t_student where name like %#{condition}%
</select>
测试类中调用方法,传参为模糊查询的内容
@Test
public void selectStudentsLikeTwo() throws IOException {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
List<Student> students = dao.selectStudentsLikeTwo("战");
students.forEach(student -> System.out.println(student));
sqlSession.close();
}
执行程序报错显示
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘%‘ç«™’%’ at line 1
原因分析:
mapper.xml 模糊查询拼接 % 错了
解决方案:
在 mapper 文件中,加入 % 需要加上双引号
<select id="selectStudentsLikeTwo" resultType="Student">
select * from t_student where name like "%"#{condition}"%"
</select>
执行成功