preparedStatement防止SQL注入

String url = "jdbc:mysql:///xuexi";
       String user = "root";
       String passwd = "123321";
       Connection connection = DriverManager.getConnection(url, user, passwd);
       Statement statement = connection.createStatement();
       Scanner sc = new Scanner(System.in);
       String s = sc.next();
       sc.nextLine();      //吸收一个空格
       String s2 = sc.nextLine();
       String sql = "SELECT * FROM userdim WHERE user = ? and passwd = ?";
       PreparedStatement preparedStatement = connection.prepareStatement(sql);
       preparedStatement.setString(1,s);       //将第一个?的值切换成s的值
       preparedStatement.setString(2,s2);      //将第二个?的值切换成s2的值
       ResultSet resultSet = preparedStatement.executeQuery();     //返回查询结果
       if(resultSet.next()){
           System.out.println("登录成功");
       }else {
           System.out.println("登录失败");
       }

您可能还喜欢...