Mybatis中#{}和${}的区别是什么?

时间:2021-08-29 19:11:26   收藏:0   阅读:30

是什么?

Mybatis中的#{}${}都可以把传入的参数拼到SQL中。
#{}是预编译处理、是占位符, ${}是字符串替换、是拼接符。

核心思想是:确保sql语句中 String型参数 的最外层由单引号包裹;特殊字符普通化。


为什么?

看看PreparedStatementStatement的区别:

PreparedStatement 接口是 Statement 的子接口,它表示一条预编译过的 SQL 语句,并对参数中的特殊字符进行转义,使用StringBuild对象来容纳sql语句的每个字符,最后再把StringBuild对象转String。

SQL="select * from user where username = ‘ " + username + " ‘ ";
username=hello‘; delete from user where id=‘1
最终的Sql就是
  SQL="select * from user where username = ‘ hello‘; delete from user where id=‘1 ‘";
select * from user where name = #{name} and password = #{password} 将转为
select * from user where name = ‘zhouyu‘ and password = ‘1 or 1=1‘

注意:SQL中的字符串使用单引号表示!


怎么用?

原文:https://www.cnblogs.com/Deng-23-binb/p/15202270.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!