MyBatis中使用sql字符串拼接的时候,要注意防止sql注入的问题。
首先说一下${}和#{}的区别
#{}:占位符,是以预编译的形式,将参数设置到sql语句中;PreparedStatement;防止sql注入
${}:拼接符,取出的值直接拼装在sql语句中,会有安全问题,sql注入;
实例语句中:name传入值为 李四
select * from user where name = #{name};
select * from user where name = ${name};
结果均为
select * from user where name = '李四';
但是 #{} 和 ${} 在控制台打印的预编译中的结果却不一样。
#{} 在预处理时,会把参数部分用一个占位符 ? 代替,结果为:
select * from user where name = ?;
而 ${} 则只是简单的字符串替换,结果为:
select * from user where name = '李四';
而在使用模糊查询时更需要注意通配符写的位置:
使用${}拼接,十分容易被别人SQL注入,导致数据不安全
List<User> userlist = mapper.getUserByLike("李");
<!--模糊查询-->
<select id="getUserByLike" parameterType="string" resultType="com.qyh.pojo.User">
select * from user where name like '%${value}%'
</select>
而如果使用#{}占位符,防止SQL注入,则需要把通配符写到java代码中而不是xml文件中
List<User> userlist = mapper.getUserByLike("%李%");
<!--模糊查询-->
<select id="getUserByLike" parameterType="string" resultType="com.qyh.pojo.User">
select * from user where name like #{value}
</select>