2018-05-22JDBC之sql注入攻击及防止攻击


public class JDBCdemo {
    public static void main(String args[]) throws ClassNotFoundException,SQLException{
         Class.forName("com.mysql.jdbc.Driver");
         String url="jdbc:mysql://localhost:3306/mybase";
         String users="root";
         String password="123456";
         Connection conn=DriverManager.getConnection(url, users, password);
         Statement stat=conn.createStatement();
         Scanner sc=new Scanner(System.in);
         String user=sc.nextLine();
         String pass=sc.nextLine();
         String sql="SELECT *FROM users WHERE username= '"+user+ "'AND PASSWORD ='"+pass+" ';";
         ResultSet rs=stat.executeQuery(sql);
         while(rs.next()) {
             System.out.println(rs.getString("username")+"   "+rs.getString("password"));
         }
         conn.close();
         stat.close();
         rs.close();
    }
    
}

若输入 a
1 ' or '1=1
则为登入成功 显示为 
a   1
b   2
public class JDBCdemo {
    public static void main(String args[]) throws ClassNotFoundException,SQLException{
         Class.forName("com.mysql.jdbc.Driver");
         String url="jdbc:mysql://localhost:3306/mybase";
         String users="root";
         String password="123456";
         Connection conn=DriverManager.getConnection(url, users, password);
        
         Scanner sc=new Scanner(System.in);
         String user=sc.nextLine();
         String pass=sc.nextLine();
         String sql="SELECT *FROM users WHERE username= ? AND PASSWORD =?;";
        PreparedStatement pst=conn.prepareStatement(sql);
        pst.setObject(1, user);
        pst.setObject(2, pass);
        ResultSet rs=pst.executeQuery();
         while(rs.next()) {
             System.out.println(rs.getString("username")+"   "+rs.getString("password"));
         }
         conn.close();
         pst.close();
         rs.close();
    }
    
}

你可能感兴趣的:(2018-05-22JDBC之sql注入攻击及防止攻击)