在学习JDBC时,使用Statement接口会有如下SQL注入的漏洞.
由于没有对拼接的字符串进项检查,很容易遭受到恶意攻击,例如编程如下:
例如变成如下操作。
select * from user where username='aaa' or '1'='1' and password='bbb' or '1'='1';
解决SQL注入的漏洞的方法是使用PreparementStatement接口,以下是PreparementStatement接口的使用方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class PreparedStatmentTest { @Test public void testPreparedStatement() throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql:///test", "root", "abc123"); User user = new User(null, "张飞", "123456", "zhangfei@sanguo.com"); String sql = "select * from user where username = ? and password = ?"; PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1, user.getUsername()); pst.setString(2, user.getPassword()); ResultSet rs = pst.executeQuery(); System.out.println(rs.next()); conn.close(); pst.close(); rs.close(); } }
|