select * from table_name where id=#{id}; select * from table_name where id=${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 ${tableName} where name = #{name}
當tableName為 " user; delete user; --"時,SQL將被解析為:
select * from user; delete user; -- where name = ?;
這樣就造成了嚴重后果(-- 等於注釋)。
參考:http://blog.csdn.net/pfnie/article/details/53230994