凌潇萧,校园混混道路,新能源汽车价格表
本人微信公众号,欢迎扫码关注!
在具体改造时,必须使用preparedstatement来防止sql注入,普通sql语句比较容易改造,本重点探讨在拼接查询条件的时候如何方式sql注入,具体思路请参考下面的示例代码。
@test public void statementtest() { string username = "tom"; string sex = "1"; string address = "' or '1'='1"; statement stat = null; resultset res = null; connection conn = connectionfactory.getconnection(); string sql = "select * from user where 1 = 1"; sql += username == null ? "" : " and username = '" + username + "'"; sql += sex == null ? "" : " and sex = '" + sex + "'"; sql += address == null ? "" : " and address = '" + address + "'"; system.out.println(sql); try { stat = conn.createstatement(); res = stat.executequery(sql); printres(res); } catch (sqlexception e) { e.printstacktrace(); } finally { resourceclose.close(res, stat, conn); } }
select * from user where 1 = 1 and username = 'tom' and sex = '1' and address = '' or '1'='1' 10 tom 2014-07-10 1 beijing 16 tom 2018-07-31 1 shanghai 22 tom 2019-04-16 2 shanghai 24 tom 2019-06-22 1 guangzhou 25 tom 2019-01-22 2 guangzhou 28 tom 2018-07-31 1 shenzhen
别担心,此时我们使用一个小小的技巧,具体参考下面的示例代码
@test public void preparestatementtest() { string username = "tom"; string sex = null; string address = "' or '1'='1"; preparedstatement stat = null; resultset res = null; connection conn = connectionfactory.getconnection(); string sql = "select * from user where 1 = 1"; list<object> param = new arraylist<>(); if (username != null) { sql += " and username = ?"; param.add(username); } if (sex != null) { sql += " and sex = ?"; param.add(sex); } if (address != null) { sql += " and address = ?"; param.add(address); } system.out.println(sql); try { stat = conn.preparestatement(sql); for (int i = 0; i < param.size(); i++) { stat.setobject(i+1,param.get(i)); } res = stat.executequery(); printres(res); } catch (sqlexception e) { e.printstacktrace(); } finally { resourceclose.close(res, stat, conn); } }
select * from user where 1 = 1 and username = ? and address = ?
但进行类似条件拼接这种操作时,可以先把参数放入一个集合中,然后遍历集合,同时利用setobject(index,obj)这个方法就可以动态的获取参数的索引了,而且不用关心参数是何种类型。
如果实在避免不了使用的话一定要使用可以需编译的preparestatement对象,避免被sql注入带来的风险。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论