天天看点

Mybatis中sql语句 # 和 $的区别

写mabatis的 sql语句时遇到的关于# 和 $ 使用问题,今天做一下总结。

传入参数:(@param(“ids”),string ids);

sql语句 : select * from t where id in (#{ids});

结果: 当ids传入为string 1,2,3 时,得出效果只是查到了id=1的数据

原因: 原来#{xxx}是一个字符串,mybatis只会当他是一个值,解析成sql语句相当于 select * from t where id in “1,2,3”,此时 1,2,3相当于一个字符串。

解决办法1:想实现查多条效果,用${ids}

把ids当成字符串传进来

解决办法2:

select * from t where id in #{id}。注意要把ids对象成数组[1,2,3]才生效。

1、 #是将传入的值当做字符串的形式,eg:select id,name,age from student where id =#{id},当前端把id值1,传入到后台的时候,就相当于 select id,name,age from student where id =‘1’.

2、$ 将传入的值直接显示生成sql语句,eg:select id,name,age from student where id =${id},前端把id值1,传入到后台的时候,就相当于 select id,name,age from student where id = 1.

3、#方式能够很大程度防止sql注入,$方式无法防止sql注入

继续阅读