JDBC-Sql防注入

来源:互联网 发布:linux编辑文件的命令 编辑:程序博客网 时间:2024/05/17 06:22

JDBC链接数据库查询相关信息时,传入参数进行查询等操作,可以拼接字符串,例如:

String querySQL = "select * from Student where studentId = '13010001'";ConnectionUtils connection = ConnectionUtils.getConnection();Statement stmt = connection.prepareStatement(querySQL);ResultSet rs = stmt.executeQuery();
(ConnectionUtils工具类详情见 【工具类】一、ConnectionUtil工具类)

其中,sutdentId属性在传入的过成功,可引起SQL注入,如:将'13010001'替换成'13010001' or 'a' = 'a' 。由于'a' = 'a' 恒成立,则sql语句一定可以执行


所以,为防止SQL注入,可以利用PreparedStatement来防止SQL注入。用法如下:

String querySQL = "select * from Student where studentId = ?";ConnectionUtils connection = ConnectionUtils.getConnection();PreparedStatement stmt = connection.prepareStatement(querySQL);stmt.setString(1,str);ResultSet rs = stmt.executeQuery();

PreparedStatement的处理方式是,将str的内容作为一个字符串赋给querySQl语句中的?。所以,如果被传参数为'13010001' or 'a' = 'a',那做为该字段的对应值,显然这样是没有任何查询结果的。



0 0
原创粉丝点击