使用准备好的语句时应用程序未验证用户

Application not validating user when using prepared statement

我最初使用以下代码来验证有效的用户登录

 public static boolean validate(String name, String password) {
        boolean status = false;
        try {
            Connection con = DB.getConnection();
            String select = "select * from Librarian where UserName= '" + name + "' and Password='"+ password +"'";
            Statement selectStatement = con.createStatement();
            ResultSet rs = selectStatement.executeQuery(select);
          
            status = rs.next();
            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        return status;
    }

我看到使用准备好的语句更好,上面的语句容易受到 SQL 注入。下面是我尝试使用的代码

public static boolean validate(String name, String password) {
        boolean status = false;
        try {
            Connection con = DB.getConnection();
            PreparedStatement ps = con.prepareStatement("select * from Librarian where UserName= ? and password = ?");
            ps.setString(1, name);
            ps.setString(2, password);       
            ResultSet rs = ps.executeQuery();
            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        return status;
    }

这不是在验证用户,我无法访问该应用程序。任何帮助将不胜感激。

您错过了 status = rs.next();

public static boolean validate(String name, String password) {
  boolean status = false;
  try {
    Connection con = DB.getConnection();
    PreparedStatement ps = con.prepareStatement("select * from Librarian where UserName= ? and password = ?");
    ps.setString(1, name);
    ps.setString(2, password);
    ResultSet rs = ps.executeQuery();
    status = rs.next();
    con.close();
  } catch (Exception e) {
    System.out.println(e);
  }
  return status;
}