MyBatis中使用 和 的區別

2022-01-24 14:46:47 字數 779 閱讀 8840

select * from table_name where id=#;

select * from table_name where id=$;

區別:在動態sql解析階段,#{}會被解析為jdbc預編譯語句的引數標記符(佔位符),例如上面的#{}語句將被解析為:

select * from table_name where id=? ;

而${}則直接解析為字串變數替換,當變數id的傳參為"xiaoming"時,上面的${}語句將被解析為:

select * from table_name where id='xiaoming';

也就是說,對於變數替換,#{}發生在dbms中,而${}發生在動態sql解析階段。

實際使用:

1、當變數為表名時,只能使用${},這是因為#{}解析的佔位符在進行變數替換時,會帶上單引號' ',表名帶單引號會導致sql錯誤。

2、除了上面第1條之外,能用#{}的地方盡量用#{},這是因為相同的預編譯sql可以復用,用#{}能夠節能開銷提高效能;${}會引起sql注入問題,例如:

select * from $ where name = #

當tablename為 " user; delete user; --"時,sql將被解析為:

select * from user; delete user; -- where name = ?;

這樣就造成了嚴重後果(-- 等於注釋)。

參考:

MyBatis中使用 和 的區別

select from table name where id select from table name where id 區別 在動態sql解析階段,會被解析為jdbc預編譯語句的引數標記符 佔位符 例如上面的 語句將被解析為 select from table name where id 而...

mybatis和ibatis使用區別

select from userinfo where userid userid select from userinfo where userid public userinfo getuserinfo int userid 2.等元素的 parameterclass 屬性改為了 paramete...

MyBatis中使用foreach迴圈的坑及解決

目錄 我們首先看一段mybatis中使用foreach迴圈的sql select from table where id in 這段sql執行會新增幾個佔位符,正確寫法foreach寫到一行 select from t程式設計客棧able where id in 傳進來的 list 肯定有值得,本身...