5 登录示范(解决注入问题)

1.对于准备状态的认识

 con = JDBCutil.getCon();
            String sql="select * from user1 where name=? and password=?";
            //使用准备状态解决注入问题
             preparedStatement = con.prepareStatement(sql);
            //给占位符对号入座
            preparedStatement.setString(1,name);
            preparedStatement.setString(2,pass);

            resultSet = preparedStatement.executeQuery();

2.登录方法

 public boolean login(String name,String pass){
        Connection con=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        if(name==null||pass==null){
            return false;
        }
        try {
            con = JDBCutil.getCon();
            String sql="select * from user1 where name=? and password=?";
            //使用准备状态解决注入问题
             preparedStatement = con.prepareStatement(sql);
            //给占位符对号入座
            preparedStatement.setString(1,name);
            preparedStatement.setString(2,pass);

            resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                return true;
            }


        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            JDBCutil.close(preparedStatement,con,resultSet);
        }
        return false;
    }

3.psvm的完善

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名");
        String name = scanner.nextLine();
        System.out.println("请输入密码");
        String pass = scanner.nextLine();
        boolean login = new Damo4().login(name,pass);


        if(login){
            System.out.println("登陆成功");
        }else {
            System.out.println("登录失败");
        }
    }

4.用户表
5 登录示范(解决注入问题)_第1张图片
5.结果

请输入用户名
jiang
请输入密码
123
/C:/Users/Administrator/IdeaProjects/JDBC/out/production/JDBC1/JDBC.properties
登陆成功

Process finished with exit code 0

6.错误警醒

 preparedStatement.setString(1,"name");
 preparedStatement.setString(2,"pass");

你可能感兴趣的:(JDBC)