Adnan
Adnan

Reputation: 4607

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 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();
      }
    }
}

Upvotes: 0

Views: 1632

Answers (3)

Skip Head
Skip Head

Reputation: 7760

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

Upvotes: 0

user330315
user330315

Reputation:

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.

Upvotes: 2

maks
maks

Reputation: 6006

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();
      }
    }
}

Upvotes: 0

Related Questions