MyBatis之#{} and ${}

  • 2019 年 10 月 6 日
  • 笔记

#{} 和 ${} 之间最大的差别就是 #{}会在使用的时候被加上 ‘’ 引号, ${}直接传值,不做任何处理

1.#{}对传入的参数会做预编译,也就是会当做字符串来处理  

select * from info where name =  #{name}  比如传递 博客园,得到的结果就是如下  select * from info where name = '博客园'

2.${}对传入的参数不会做任何的处理,也就是说传递什么就是什么

select * from info where name = ${name]  比如传递  博客园  得到的结果就是如下  select * from info where name = 博客园

3.#{} 最大的好处就是可以很大程度上防止SQL注入(SQL Injection),然而${}则不具备这样的功能

比如我们在做用户登录的场景  使用#{}  select * from user where userCode = #{userCode} and userPwd = #{userPwd}  前台传递:userCode = 123     userPwd = 123 or 1 = 1  后台解析后,MyBatis首先会对SQL语句的参数用 ‘?’做预编译处理  select * from user where userCode = ? and  userPwd = ?;  最终效果:  select * from user where userCode = '123' and userPwd = '123 or 1 = 1';  这样就可以有效的防止了sql的注入效果    使用${}  select * from user where userCode = ${userCode} and userPwd = ${userPwd}  前台传递:userCode = 123     userPwd = 123 or 1 = 1  后台解析后,MyBatis会直接把值传递给sql,不做任何的处理!  最终效果:  select * from user where userCode = 123 and userPwd = 123 or 1 = 1;  不仅可能导致语法错误!而且更严重的会对导致用户恶意注入sql获取信息,或者做其它恶意操作!!非常危险!

4.说了这么多#{}的好处,好像${}被遗弃的婴儿一样(委屈),但是${}也是有很大作用的!如下:

比如我们在直接想用SQL语句插入一条原封不动的参数的时候,如order by我们的${}就派上用场了()  select * from info order by ${name}

重点:SQL注入是非常可怕的!!!(搞不好被罚工资或者直接牢底坐穿)!一定要注意使用场景!