MyBatis如何防止SQL注入

下面是MyBatis一个Dao配置

    <select id="findRank" parameterType ="String" resultType="String">
        SELECT u.name FROM UserInfo u
            where 1=1
            and u.UserID=#{userID} ;    
    </select>

打印出执行的SQL语句


 SELECT u.name FROM UserInfo u where 1=1 and u.UserID=?     

这是因为MyBatis启用了预编译功能,在SQL执行前,会先将上面的SQL发送给数据库进行编译;执行时,直接使用编译好的SQL,替换占位符“?”就可以了。因为SQL注入只能对编译过程起作用,所以这样的方式就很好地避免了SQL注入的问题。
【底层实现原理】
MyBatis是如何做到SQL预编译的呢?其实在框架底层,是JDBC中的PreparedStatement类在起作用,PreparedStatement是我们很熟悉的Statement的子类,它的对象包含了编译好的SQL语句。这种“准备好”的方式不仅能提高安全性,而且在多次执行同一个SQL时,能够提高效率。原因是SQL已编译好,再次执行时无需再编译。

话说回来,是否我们使用MyBatis就一定可以防止SQL注入呢?当然不是,请看下面的代码:

    <select id="findRank" parameterType ="String" resultType="String">
        SELECT u.name FROM UserInfo u
            where 1=1
            and u.UserID=${userID} ;   
    </select>

假设userID=1,将SQL打印出来是这样的:

 SELECT u.name FROM UserInfo u where 1=1 and u.UserID=1

假如:
userID=1;drop table UserInfo ;那么sql是这样的

 SELECT u.name FROM UserInfo u where 1=1 and u.UserID=1;drop table UserInfo ;
 测试结果

 SELECT u.name FROM UserInfo u  where 1=1   and u.UserID=1;drop table UserInfo;
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'drop table UserInfo' at line 3
直接报异常,你应该庆幸mybaties做了处理,但是不管怎么说${xxx}是无法阻止SQL注入的。

“${xxx}”
缺点: 直接参与SQL编译,不能避免注入攻击。
优点:及到动态表名和列名时,只能使用“${xxx}”这样的参数格式
注意: 这样的参数需要我们在代码中手工进行处理来防止注入。

“#{xxx}“
相当于JDBC中的PreparedStatement
${}:是输出变量的值
优点:#{}是经过预编译的,是安全的;

转载于:https://www.cnblogs.com/feiZhou/p/9344025.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值