MyBatis中使用#{}和${}的区别

 

select * from table_name where id=#{id};

select * from table_name where id=${id}; 

区别:java

在动态SQL解析阶段,#{}会被解析为JDBC预编译语句的参数标记符(占位符),例如上面的#{}语句将被解析为:性能

select * from table_name where id=? ;

  而${}则直接解析为字符串变量替换,当变量id的传参为"xiaoming"时,上面的${}语句将被解析为:.net

select * from table_name where id='xiaoming';

  也就是说,对于变量替换,#{}发生在DBMS中,而${}发生在动态SQL解析阶段。blog

实际使用:字符串

一、当变量为表名时,只能使用${},这是由于#{}解析的占位符在进行变量替换时,会带上单引号' ',表名带单引号会致使SQL错误。编译

二、除了上面第1条以外,能用#{}的地方尽可能用#{},这是由于相同的预编译SQL能够复用,用#{}可以节能开销提升性能;${}会引发SQL注入问题,例如:table

select * from ${tableName} where name = #{name} 

  当tableName为 " user; delete user; --"时,SQL将被解析为:class

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

  这样就形成了严重后果(-- 等于注释)。变量

 

参考:http://blog.csdn.net/pfnie/article/details/53230994select

相关文章
相关标签/搜索