sql注入的安全性问题
在使用 Statement 类执行 sql 对象时,拼接的 sql 语句可能会有特殊关键子参与字符串拼接,造成数据库信息泄露等问题。
使用 Statement 类的 sql 语句格式:
String sql = "select *from admin where name = '"+username+"' and password = '"+password+"'";
当遇到 sql 注入语句:
请输入用户名:
abcdefg
请输入密码:
s' or 'a' = 'a
select * from user where username = 'abcdefg' and password = 's' or 'a' = 'a'
登录成功!
可以看到 sql 语句不管用户名和密码是什么,该语句都会正确执行,登录成功并获得所有用户信息!
解决方法
为了避免恶意的 sql 注入,就要用到 PreparedStatement 类:
String sql = "select *from admin where aname = ? and apassword = ?";
执行语句为:
pstmt = conn.prepareStatement(sql);
赋值语句为:
pstmt.setString(1,username);
pstmt.setString(2,password);
执行结果为:
请输入用户名:
abcdefg
请输入密码:
s' or 'a' = 'a
登录失败,用户名或密码错误!
成功避免了 sql 注入。