Skip to content
Advertisement

Else statement not executing inside while loop of SQL database

Else statement not working inside while loop

public void loginButton() throws ClassNotFoundException, SQLException{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/finditdb","root","root");
        Statement stmt = con.createStatement();
        String usernameInput = usernameField.getText();
        String passwordInput = passwordField.getText();
        ResultSet rs = stmt.executeQuery("SELECT * FROM finditdb.login WHERE username like '" + usernameInput +"' and password like '" + passwordInput +"'");
        while(rs.next()){
            String usernameDb = rs.getString("username");
            String passwordDb = rs.getString("password");
            if(usernameInput.equals(usernameDb) && passwordInput.equals(passwordDb)){
                System.out.println("Access Granted..");
            }
            else {
                System.out.println("Access denied..");
            }
        }
    }

Advertisement

Answer

You could try this and let me know if it works the way you want it to.

while(true){     
     if(rs.next()){
        String usernameDb = rs.getString("username");
        String passwordDb = rs.getString("password");
        if(usernameInput.equals(usernameDb) && passwordInput.equals(passwordDb)){
            System.out.println("Access Granted..");
            break;
          }

     }

     else{
            System.out.println("Access denied..");
            break;
     }
    }

We haven’t mentioned any exit condition within the while loop parenthesis, so the loop keeps running till no more records are left to be fetched (else will print Access denied and break) or if access is granted (breaks again).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement