3

This is a code for a login form where i used JDBC connection the code has no error but when i run it it always goes to else statement

    Connection con;
    Statement st;
    ResultSet rs;
    try{
      Class.forName("java.sql.Driver");
      con=DriverManager.getConnection   ("jdbc:mysql://localhost/database","root","password");
      st=con.createStatement();
      rs=st.executeQuery("select * from users;");
      while(rs.next()){
                String userID=rs.getString("userID");
                String password=rs.getString("password");

                if(userID.equals(txtuserID.getText())
                    && (password.equals(txtpassword.getPassword())) {
                // ***HERE IS MY PROBLEM I WANT TO CHECK IF WHATS IN THE 
                // TEXT FIELD OR PASSWORD FIELD IS THE SAME FROM MySQL***
                    JOptionPane.showMessageDialog(null,"you have logged in");
                    new MainForm().setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(null,"Incorrect username and password");
                }
     }
  } catch(Exception e) {
     JOptionPane.showMessageDialog(null,"Error in Connectivity: " +e.getMessage());
  }  
Manu
  • 1,474
  • 1
  • 12
  • 18
Farah Toghan
  • 33
  • 1
  • 3

2 Answers2

5

The JPasswordField getPassword() method returns char[]. Convert to String before comparison : ( actually construct a new String with those chars ...)

if(userID.equals(txtuserID.getText()) &&
  (password.equals(new String((txtpassword.getPassword()))) {
}
chenchuk
  • 5,324
  • 4
  • 34
  • 41
1

Regarding chenchuk's answer, it would be much more secure to leave char arrays as char arrays and not convert them to a String, which can be stolen much more easily.

So instead of converting the password's char[] to String as in chenchuk's answer:

if(userID.equals(txtuserID.getText()) &&
  (password.equals(new String((txtpassword.getPassword()))) {
}

It is much safer to do use the java.util.Arrays.equals(...) method:

if(userID.equals(txtuserID.getText()) 
        && Arrays.equals(txtpassword.getPassword(), password.toCharArray())) {

    // your code goes here
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • This is very true, however, you are still not handling it correctly if that is your concern. See https://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords – YoYo Nov 05 '17 at 18:55