sql注入与预防
如果使用Statement进行查询
sql是接收输入框输入 进行拼装的输入框中 如果输入了sql语句 比如 " "zhangsan1asdfadsf 'or' 1==1","1==1 'or' 12aasdfadsf3""
实际上 这不是一个普通的字符串 而是一个sql语句 这个sql语句 会改变 拼装后的sql的判断条件的逻辑 从而返回错误的结果
这种现象就叫SQL注入
预防sql注入的解决方案
不要使用statement执行直接拼装的sql
要使用PreparedStatement 这个类会把跟sql相关的字符串 在组拼sql的时候做转义从而预防sql注入
public class JDBCLogin {public static void main(String[] args) {// boolean login = login("zhangsan","123");boolean login = login("admin 'or' 1==1","1==1 'or' 12aasdfadsf3");if(login){System.out.println("登录成功");}else{System.out.println("登录失败");}}public static boolean login(String username,String password){Connection conn = JDBC_Utils.getConn();try {//Statement statement = conn.createStatement();String sql1 = "select * from user where username = ? and password = ?";PreparedStatement prepareStatement = conn.prepareStatement(sql1);prepareStatement.setString(1, username);prepareStatement.setString(2, password);// String sql = "select * from user where username = '"+username+"' and password = '"+password+"'";// ResultSet resultSet = statement.executeQuery(sql);ResultSet resultSet = prepareStatement.executeQuery();if(resultSet.next()){return true;}else{return false;}} catch (Exception e) {e.printStackTrace();return false;}}}
select * from user where username = 'zhangsan1asdfadsf 'or' 1==1' and password = '1==1 'or' 12aasdfadsf3'