SQL注入命令优化

SQL注入命令优化

优化命令:将Statement 替换成了 PreparedStatment预编译命令对象

SQL注入命令优化

SQL注入命令优化

未使用预编译对象,会导致sql注入问题. 密码输入啥都可以登录成功

@Test
    //登录
    public void login() throws SQLException {
        Connection connection = JdbcUtils.getConnection();
        Statement statement = connection.createStatement();
        String name = "'or 1=1 #";
        String password = "asdasdsad";
        ResultSet resultSet = statement.executeQuery("select * from user where name = '"+name+"' and password = '"+password+"'");
        if(resultSet.next()){
            System.out.println("登录成功!!");
        }else{
            System.out.println("登录失败!!!");
        }
    }

使用预编译对象后,解决用户名、密码随便输入都可以的问题

 @Test
    //登录
    public void login() throws SQLException {
        Connection connection = JdbcUtils.getConnection();
        //Statement statement = connection.createStatement();   不再使用Statment 存在sql注入的bug
        PreparedStatement preparedStatement = connection.prepareStatement("select * from user where name = ? and password = ?"); //预编译
        String name = "lisi";
        String password = "123";
        //此时preparedStatement中 占位符还没有存值,因此需要通过方法传入用户输入的值
        preparedStatement.setObject(1,name);
        preparedStatement.setObject(2,password);
        ResultSet resultSet = preparedStatement.executeQuery();
        if(resultSet.next()){
            System.out.println("登录成功!!");
        }else{
            System.out.println("登录失败!!!");
        }
        resultSet.close();
        preparedStatement.close();
        JdbcUtils.close();
    }
上一篇:JDBC(Java连接数据库)的操作步骤


下一篇:题5 Statement,PreparedStatement和CallableStatement的区别