Check username and password in java DataBase and give wrong password message if false

prince_ade picture prince_ade · Nov 19, 2013 · Viewed 52.9k times · Source

i want to display an error wrong username & password after comparing entered username and password with database of users in java.

the problem is it does the if else statement against each row until it gets to the right row b4 displaying "username and password correct" but i want it to check against all and if it doesn't exist then it displays "Please Check Username and Password "

note: please ignore the naming convention the problem is in the arrangement of the while, if and any other recommended loop statements but i am not sure on how to organise it to get my desired result

here is my code with comments

 public void displayUsers(String f, String s) {
        try {
            String queryString = "SELECT SName, SPwd FROM staff";
            ResultSet results = Statement.executeQuery(queryString);

            while (results.next()) {
            String staffname = results.getString("snameeee");
            String password =  results.getString("SPwd");

               if ((f.equals(staffname)) && (s.equals(password))) {

                  JOptionPane.showMessageDialog(null, "Username and Password exist");  
            }else {

             //JOptionPane.showMessageDialog(null, "Please Check Username and Password ");
            }
            results.close();
        } catch (SQLException sql) {

            out.println(sql);
        }

Answer

Suresh Atta picture Suresh Atta · Nov 19, 2013

No, what you are doing is wrong.

Loading all records is not good practice to check credentials.

Pass username parameter to your query and check in database.

1)If no user exists, tell username not exists.

2)If user exists then check password of with existed database user password.