使用Statement执行查询语句的时候 :
比如要执行用户名 密码登录验证的sql语句 经常要输入 String sql = " select * from login where name=' " +name+ " ' and pwd = ' " +pwd+ " ' ";
这时候如果用户输入的密码是 ' or '1' = '1
这时候 整条输出语句可以拼装为 select * from login where name='xx' and pwd =' ' or '1' = '1'
因为 '1' = '1' 永远为true 相当于 select * from login; 会把表中所有数据都查出来 甚至可能进行修改、删除
而使用PreparedStatement 就可以防止sql注入方式 是因为 它进行了循环遍历:
首先这个类进行语句执行不是直接进行语句的拼接,而是先进行预编译,用? 进行占位 再set()的时候 将属性左右加上 ' (int类型不会)
然后会把用户输入的所有字符集全部遍历 如果识别出 一些特殊字符 比如 换行符、\ 、双引号、单引号 还有一些特殊字符 会进行编译
比如还是输入刚才的密码 会变成 select * from login where name='xx' and pwd =' \' or \'1\' = \'1\' '
所以使用了PreparedStatement 就 无法截断SQL语句,也就是说 无法拼接SQL语句,防止了sql注入。
参考原文:https://blog.csdn.net/qq_39740629/article/details/77719468