Mybatis中#{}号与${}的区别
Mybatis中#{}号与${}的区别
#{}:
- 使用
#{}会将传入的值进行预编译(在使用jdbc的preparedStatement, Connector/J在5.0.5以后的版本, 需要设置useServerPrepStmts参数为true, 默认是false. 详见探究mysql预编译或者JDBC:深入理解PreparedStatement和Statement), 在使用#{}时形成的sql语句已经带有引号, 例:select * from table where id=#{id}, 当传入的id=66时, 在调用这个语句时后台打印出的sql为:select * from table where id='66', 在组成sql语句的时候把参数默认为字符串.
${}:
- 使用`
{id}
, 传入的id=66时, 后台打印为:select * from table where id=66`.
#{}这种方式可以可以防止sql注入: 用户进行一个登录操作, 后台sql验证式样为: select * from user where username=#{name} and password = #{pwd}, 如果用户输入的用户名为"admin", 密码是"1 or 1=1", 用#{}时, sql的语句为:select * from user where username='admin' and password = '1 or 1=1'; 而如果换成$方式, sql语句为select * from user where username=admin and password = 1 or 1=1. 这样就形成了sql注入.
能用#{}则用它,这样可以防止sql注入, 当需要原样输出时才使用${}. 例如:
select * from ${table_Name} order by ${column_name}这里需要传入表名和某列名, 然后按照某列进行排序, 假如传入student、studentname 则语句为:select * from student order by studentname.如果是使用
#{}则变成了select * from 'student' order by 'studentname', 这样就不对了.
