前提知识点。
1、预编译是提前对SQL语句进行预编译,而其后注入的参数将不会再进行SQL编译。
2、SQL注入是发生在编译的过程中,因为恶意注入了某些特殊字符,最后被编译成了恶意的执行操作。
而预编译机制则可以很好的防止SQL注入。
3、Concat返回结果为连接参数产生的字符串。如有任何一个参数为NULL ,则返回值为 NULL。
mysql> select concat('11','22','33');
| 112233 |
mysql> select concat('11','22',null);
| NULL |
功能原理:
mybatis提供#{value}与${value}这2种方式的动态传参。其具体工作原理如下:
1、在sql中解析时候
#传入的参数在SQL中显示为字符串
eg:select id,name,age from student where id =#{id},
当前端把id值1,传入到后台的时候,就相当于 select id,name,age from student where id ='1'.
$传入的参数在SqL中直接显示为传入的值
eg:select id,name,age from student where id =${id},
当前端把id值1,传入到后台的时候,就相当于 select id,name,age from student where id = 1.
2、在预编译阶段
#{ } 被替换为一个参数占位符 ?。
${}: 仅仅为一个纯碎的 string 替换,就是把${}替换成变量的值。
因此易发生sql注入
eg:select * from ${tableName} 若tableName为user; delete user; --,则 直接执行删除操作。
#{}在一定程度上可以防止sql注入。
3、试用情况
#{}方式一般用于传入字段值,并将该值作为字符串加到执行sql中,一定程度防止sql注入;
${}方式一般用于传入数据库对象,例如传入表名,不能防止sql注入,存在风险。
模糊查询中,使用$.
若使用#:select * from reason_detail where reason_en like '%#{reason}%',会解析为like '%' reason '%'(报错Parameter index out of range (2> number of parameters, which is 1). ,'%'为一个条件了)
传入order by 后边的参数使用$。
4、替代方法
可以使用concat将字符串连接起来为一个字符串,不同的数据库还有不同的处理方法。