#{} 和 ${} 之間最大的差別就是 #{}會在使用的時候被加上 ‘’ 引號, ${}直接傳值,不做任何處理
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注入是非常可怕的!!!(搞不好被罰工資或者直接牢底坐穿)!一定要注意使用場景!