Search code examples
javaswingjdbcderbyresultset

ResultSet.next() row counter fails to count


I'm trying to figure out why this won't count and show Rows: 2 when I enter "ashton" for username and "ashton" for password. In my database I inserted 2 entries of username and password.

Here's the screenshot of table:

enter image description here

Here's the GRAB file:

enter image description here

Here's my code:

private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
    String userNameEntered = userNameTxtField.getText().trim();
    String passwordEntered = passwordTxtField.getText().trim();

    if(userNameEntered.isEmpty() || passwordEntered.isEmpty()){
        JOptionPane.showMessageDialog(this, "Please fill out all fields");
    }

    else{
    String username = "jordan";
    String password = "jordan";
    String dbURL = "jdbc:derby://localhost:1527/JDBCSTUDY";
    Connection myConnection = null;
    ResultSet myRs = null;
    String SQL = "SELECT * FROM USERS WHERE USERNAME = ? AND PASSWORD = ?";


    try {
      myConnection = DriverManager.getConnection(dbURL,username,password);
        JOptionPane.showMessageDialog(null, "Successfully Connected To Database");

        PreparedStatement myPrepStmt = myConnection.prepareStatement(SQL,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
            myPrepStmt.setString(1,userNameEntered); //assigns a string value to the first ?
            myPrepStmt.setString(2,passwordEntered); //assigns a string value to the second ?
        myRs = myPrepStmt.executeQuery(); // executes the select query and stores it to myRs


        if(myRs.next() == false){//next() method returns true if the select statement is satisfied or if query is valid
            JOptionPane.showMessageDialog(this, "Not found");
        }

        int countRows = 0;
        while(myRs.next()){
            countRows++;
            if((myRs.getString(2).equals(userNameEntered))
                && (myRs.getString(3).equals(passwordEntered))){
                JOptionPane.showMessageDialog(this,"found" +"\nRows: " + countRows );
            }
        }


    } //end of try
    catch (SQLException e) {
        //if an exception or an error even occured while executing the try{} block, the 3 lines will be printed
        System.err.println("Error message: " + e.getMessage());
        System.err.println("Error Code: " + e.getErrorCode());
        System.err.println("SQL State: " + e.getSQLState());
    }

    finally{
        if(myConnection!=null){
            try {

                myConnection.close();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null,"Error encountered: " + ex.toString());
            }
        }//end of if   
    }//end of finally
}
} 

In my understanding, next() returns true if the SELECT query is successful or if there are rows when cursor is moved by next(). I need to be able to count the rows to show that there are more than 1 row holding the same username and password. I can't proceed on making another ifelse for counting duplication of username and password because in my code, it doesn't seem to count 2 rows.

I'd appreciate any help.

Thanks.

this is the output i get, enter image description here

This is what I did, and it worked. Thanks for the suggestions guys! It's helping me learn more.

int countRows = 0;
        while(myRs.next()){
            countRows++;
        }

        if(countRows == 0)
        {
            JOptionPane.showMessageDialog(this, "User details doesn't exist. \n Please register first");
        }
        else if(countRows > 1) //if there are duplications 
        {
            JOptionPane.showMessageDialog(null, "User details found but has more 1 one entry" +
                    "\nFound: " + countRows + " users" );
        }
        else if(countRows == 1){
            JOptionPane.showMessageDialog(null, "User Found");
        }

Solution

  • Your error is to call rs.next twice: Every time you call next you are implicitly discarding the last state of the cursor. It's a good (and clearer) practice to read the resultset's columns after every call to next.

    In your case, it's enough to move if after the while loop, changing the condition:

        int countRows = 0;
        while(myRs.next()){
            countRows++;
            ...
        }
    
        if (countRows==0)
        {
            JOptionPane.showMessageDialog(this, "Not found");
        }