前言:
我們知道,在mybatis中,參數取值方式有兩種:
#{ } 和 ${ }
下面,我們來探討下#{ }與${ }不同。
?
一、#{ }
例:
select * from student where name=#{name}
編譯后執行的sql語句:
select * from student where name=?
說明:
? #{ }實現的是JDBC 中preparedStatement中的占位符。
#{ }適合sql語句中的參數傳值,構建sql語句#{ }是不可以的。
例如:
select * from #{tablename} ;
編譯后的sql語句為:
select * from ?
這在sql中是不允許的,所以要用${ 拼接}
#{ }試用的場景
1.where語句里的判斷:
????????? a=#{a},a>#{a},a in {#{a}},a like #{a}........
? 2.set語句:
???????????? set a=#{a}
3.插入語句中:
??????????? values(#{a},.......)
4.其他大部分適合${ }進行拼接
二、${ }
例:
select * from student where name=${name}
編譯后執行的sql語句:
select * from student where name=name
說明:
${ }取參方式是簡單的字符串拼接,不適合進行參數傳值,不然會有sql語句注入的危險。
它更加適合的是構建sql語句。
java中帶參數的方法。?
????????????????????????????2018-07-03