#{}
被解析为一个参数占位符?
select * from user where name = #{name};
解析
select * from user where name = ?;
${}
仅仅为一个纯碎的 string 替换,在动态 SQL 解析阶段将会进行变量替换
select * from user where ${colName} = "xxx";
解析
select * from user where name = "xxx";
${ } 的变量的替换阶段是在动态 SQL 解析阶段,而 #{ }的变量的替换是在 DBMS 中。
#{}与${}的区别可以简单总结如下:
- #{}将传入的参数当成一个字符串,会给传入的参数加一个双引号
- ${}将传入的参数直接显示生成在sql中,不会添加引号
- #{}能够很大程度上防止sql注入,${}无法防止sql注入