sql语句中#{}和${}的区别
#{}
#
将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号
eg:
order by #{user_id}
如果传入的值是1,那么解析成sql时的值为order by “1”
如果传入的值是id,则解析成的sql为order by “id”
${}
$
将传入的数据直接显示生成在sql中
eg:
order by ${userid}
如果传入的值是1,那么解析成sql时的值为order by 1
如果传入的值是id,则解析成的sql为order by id
结论:
#
方式底层采用预编译方式PreparedStatement
(预编译),能够很大程度防止sql注入;$
方式底层只是Statement
,无法防止Sql注入
$
方式一般用于传入数据库对象,例如传入表名.
一般能用#
的就别用$
注意点:
MyBatis排序时使用order by 动态参数时需要注意,用**$**而不是#
<select id="selectExistByUsernameOrPhoneOrEmail" resultType="int">
select
count(*)
from
ums_user
where
${type}=#{value}
</select>
public interface UserMapper {
int selectExistByUsernameOrPhoneOrEmail(@Param("value") String value, @Param("type") String type);
}
@Override
public void checkValue(String value, String type) {
//根据传递的参数 检查数据库是否存在数据
int count=userMapper.selectExistByUsernameOrPhoneOrEmail(value,type);
if(count>0){
if(type.equals("username")) {
throw new CoolSharkServiceException(ResponseCode.CONFLICT, "注册用户名已存在");
}
if(type.equals("phone")) {
throw new CoolSharkServiceException(ResponseCode.CONFLICT, "注册手机号已存在");
}
if(type.equals("email")) {
throw new CoolSharkServiceException(ResponseCode.CONFLICT, "注册邮箱已存在");
}
}
}
参考资料:sql 中 ${} 和 #{}的区别