Mybatis(五)#{}与${}的区别与使用
在映射文件中,有两种方式可在SQL语句中引入参数的值:
- #{}
 
<select id="selectMultiParam" resultType="cn.krain.domain.Student">
    select * from student where name=#{myname} or age=#{myage}
</select>
<!-- 经过Mybatis处理过后的SQL语句为: select * from student where name=? or age=? -->
  - ${}
 
<select id="selectMultiParam" resultType="cn.krain.domain.Student">
    select * from student where name=${myname} or age=${myage}
</select>
<!-- 经过Mybatis处理过后的SQL语句为: select * from student where name='康康' or age=23 -->
  #{}与${}的区别:
- #{}使用"?"作为占位符,使用preparedStatement对象进行预编译,效率高
 - #{}能够避免SQL注入,更安全
 - ${}是将参数与SQL拼接起来,使用Statement对象,效率低
 - 存在SQL注入风险,缺乏安全性
 - ${}可以用来替换表名或列名
 
海康威视公司福利 1149人发布
