0

I'm writing a Java program (with Java Swing and JDBC) and in one of my panels, I have a login. I want my program to compare the entered username and password and compare it to the ones U have in my database table (MySQL). This is what I wrote in my "Login" button, see for yourself:

try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    String url2 = "jdbc:mysql://localhost:3306/Students?user=root";
    Connection connect2 = DriverManager.getConnection(url2);
    Statement state2 = connect2.createStatement();
    String query2 = "select * from login_data where username='%s'";
    query2 = String.format(query2,username1.getText());
    ResultSet result2 = state2.executeQuery(query2);
    if(result2.next()){
        if(result2.getString("password")==password1.getText()){
            login.setVisible(false);
            Mainmenu();
        }else{
            result1.setText("Wrong Password");
        }
    }else{
        result1.setText("Wrong Username!!!");
    }

    state2.close();
    connect2.close();

} catch (SQLException e1) {
    e1.printStackTrace();
} catch (IllegalAccessException e1) {
    e1.printStackTrace();
} catch (InstantiationException e1) {
    e1.printStackTrace();
} catch (ClassNotFoundException e1) {
    e1.printStackTrace();
}

Now, if I give it a wrong username, it correctly shows the "wrong username" message. However, if the username is correct, it shows the "wrong password" message. It doesn't matter if the password is/isn't correct.

I feel there is a logical error here, but I can't see it.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • You should never store passwords in recoverable form. As far as your question goes check [https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839#513839](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839#513839) – suff Jul 27 '20 at 08:37
  • Your code seems fine. 1- Are you sure your password is save as clear text in the database? 2- Are you sure the column name is `password` in the database? – Morteza Jul 27 '20 at 08:39
  • `Class.forName` hasn't been necessary to load a JDBC driver for over 14 years, and `Class.forName(...).newInstance()` was only ever necessary with a very buggy version of the MySQL driver long before that.. – Mark Rotteveel Jul 27 '20 at 08:43
  • thank you! i can't believe it was such a small problem ! i replaced the "==" in my if with .equals() and it worked! – Mohammad Mehdi Roshani Jul 27 '20 at 08:43
  • The actual problem is that you are comparing strings with `==`, you need to use `equals(...)`, see the duplicate. – Mark Rotteveel Jul 27 '20 at 08:43

0 Answers0