Search code examples
javamysqlauthenticationsqlexception

Why do ResultSet APIs throw 'SQLException: Illegal operation on empty result set'?


I am adding a basic login form to my project and it gives me this error java.sql.SQLException: Illegal operation on empty result set." when the username or password doesn't match the data in the MySQL database.

If I check the result set is empty or not then the code inside that if statement does not work. However, my code runs fine without that if statement.

PLease find that section of the code below

String studentNumber = userText.getText();
String password = String.valueOf(passText.getPassword()); 

String executeQuery = "select * from login where studentNumber='"+studentNumber+"' and password ='"+password+"'" ;
ResultSet rSet = connObject.queries.executeQuery(executeQuery);// stores result of query

if(!rSet.next()){
    JOptionPane.showMessageDialog(null, "Student Number/ Password not found :(");
}
if(studentNumber.equals(rSet.getString("studentNumber"))){
    if(password.equals(rSet.getString("password"))){
        JOptionPane.showMessageDialog(null, "you are now logged in :)");

        loginFrame.setVisible(false);
        new operationClass();
    }else{
        JOptionPane.showMessageDialog(null, "password not found :(");
    }
}

Solution

  • next() has side-effects, you can't call it twice.

    You need to call it exactly once and then if it returned false, do one thing, and if true, do another. All you need is, instead of the commented out code, use an else.

    Also, use bcrypt or other password hashes, do not put passwords in a database. Also, connections and resultsets need try-with-resources protected. Also, your app is insecure (it has an SQL injection attack).

    NB: Just to head off the "But it's just for school". Well, you tell me: What's the point of learning boneheaded security practices? You can search the web for these terms ("SQL injection attacks", "password hash", "bcrypt", etcetera). You'll learn crucial information.