开发者

jdbc empty resultset check not working

In the following java class i'm having a method authenticate, in which i'm using resultSet.next() method to check that whether the given userName and password exist in the database or not, but it is returning false even when the given userName and password exist开发者_StackOverflow in the database.

public boolean authenticate(String userName,String password){
//db connection code
    try {
      String query = "select user_name from registeredUser where user_name= ? AND password = ?";
      pstmt = conn.prepareStatement(query); 
          pstmt.setString(1, userName);
      pstmt.setString(2, password);
      rs = pstmt.executeQuery();
      if(rs.next()) {  
            System.out.println("True");
                return true;
          }  
      else return false;
    } catch (Exception e) {
        e.printStackTrace();
        return False;
    } finally {
      try {
        rs.close();
        pstmt.close();
        conn.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
}


Depending on your underlying DBMS you might have a problem with the case of username and password.

For most DBMS MySecretPassword is a different value than mysecretpassword.

So, in case your DBMS is case-sensitive and the user did not enter the username and password exactly the same it's stored in the database it is very likely that the SELECT returns nothing.


Try the next code:

public boolean authenticate(String userName,String password){
//db connection code
    try {
      String query = "select count(*) from registeredUser where user_name= ? AND password = ?";
      pstmt = conn.prepareStatement(query); 
          pstmt.setString(1, userName);
      pstmt.setString(2, password);
      rs = pstmt.executeQuery();
      rs.next();
      int count = rs.getInt(1);
      if(count != 0) {  
            System.out.println("True");
                return true;
          }  
      else return false;
    } catch (Exception e) {
        e.printStackTrace();
        return False;
    } finally {
      try {
        rs.close();
        pstmt.close();
        conn.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
}


In the comments to the OP you say "i'm having following values in the db. userName:usman,password:2" but your code says the user name field is called "user_name".

userName != user_name

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜