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

2018-04-21  本文已影响0人  叫我小码哥

1.将Mapper.xml中的SQL语句解析为JDBC一个预编译指令时不同。

使用#{}时

select * from Student where stuName = #{}

这句SQL语句会被解析为

select * from Student where stuName = ?

使用¥{}

select * from Student where stuName = ${}

这句SQL语句会被解析为

select * from Student where stuName = "张三"

从上述可以看出,#{}代表了一个占位符,#{}的替换是在数据库中执行时替换。而{}代表了SQL拼接符,{}的替换是在解析阶段就替换完成。

2.使用上

符号#{}代表占位符,可以防止SQL注入。
在使用#{}时不能使用在SQL语句的表名处,只能使用在SQL语句的条件处。

select * from #{} where stuName = #{}

解析为

select * from 'student' where stuName = '张三'

这时SQL语句就存在语法上的问题。
${}不能防止SQL注入。

select * from ${table} where stuName = ${stuName} 

我们讲传入的table的值设置为 student;drop database studata; --
传入的stuName 设置为 张三;
被解析后为

select * from student; drop database studata; -- where stuName = '张三'

这条SQL语句的执行删除整个studata数据库。

上一篇 下一篇

猜你喜欢

热点阅读