做網(wǎng)站jsp和php/成功營銷十大經(jīng)典案例
sql防注入 | 底層 | jdbc類型轉(zhuǎn)換 | 當(dāng)簡單類型參數(shù) | |
$ | 不防止 | Statment | 不轉(zhuǎn)換 | value |
# | 防止 | preparedStatement | 轉(zhuǎn)換 | 任意 |
除模糊匹配外,杜絕使用${}
MyBatis教程,大家可以借鑒? ? ?MyBatis 教程_w3cschool
主要區(qū)別
1、#{} 是預(yù)編譯處理,${} 是直接替換;
2、${} 存在SQL注入的問題,而 #{} 不存在;
#{}?是預(yù)編譯處理,像傳進(jìn)來的數(shù)據(jù)會(huì)加個(gè)" "(#將傳入的數(shù)據(jù)都當(dāng)成一個(gè)字符串,會(huì)對(duì)自動(dòng)傳入的數(shù)據(jù)加一個(gè)雙引號(hào))
${}?就是字符串替換。直接替換掉占位符。$方式一般用于傳入數(shù)據(jù)庫對(duì)象,例如傳入表名.
使用 ${} 的話會(huì)導(dǎo)致 sql 注入。什么是 SQL 注入呢?
比如 select * from user where id = ${value}? ? ? ? value 是一個(gè)數(shù)值。
如果對(duì)方傳過來的是 001 ?and name = tom。這樣就相當(dāng)于多加了一個(gè)條件,把SQL語句直接寫進(jìn)來了。如果是攻擊性的語句,則會(huì)導(dǎo)致數(shù)據(jù)庫損壞。
所以為了防止 SQL 注入,能用 #{} 的不要去用 ${}。如果非要用 ${} 的話,那要注意防止 SQL 注入問題,可以手動(dòng)判定傳入的變量,進(jìn)行過濾,一般 SQL 注入會(huì)輸入很長的一條 SQL 語句。
like模糊查詢
${} 進(jìn)行模糊查詢(存在?SQL 注入問題)
方式一:直接替換
<select id="getUserById" resultType="com.by.pojo.User">select * from user where username like '%${key}%'
</select>方式二:使用concat進(jìn)行字符串拼接
<select id="getUserById" resultType="com.by.pojo.User">select * from user where username like concat('%', '${key}', '%')
</select>
#{} 模糊查詢
<select id="getUserById" resultType="com.by.pojo.User"> select * from user where username like concat('%', #{key}, '%')
</select>
使用 #{} 傳入的參數(shù)會(huì)自帶引號(hào)
<select id="getUserById" resultType="com.by.pojo.User"> select * from user where username like concat('%', #{key}, '%')
</select>目標(biāo)sql 語句:select * from user where username = '%張%';實(shí)際sql語句:select * from user where username = '%' 張 '%';