Search code examples
javasqlresultset

SQL ResultSet is empty despite having a row returned in tests


I am building a simple program for a library database system in Java where patrons can borrow and return books. The database has 4 tables: Book, Author, Patrons, and AuthorIds. I'm using the SQL statement below to retrieve 1 row of data that includes everything plus a column that counts how many books the patron has already borrowed. The problem is that the program never goes into the while(res.next()) loop and I think it's because the result set is empty. The test print doesn't get printed and membID doesn't get changed to the MemberID of the patron.

But when I try that same SQL statement on db browser on the same database it returns 1 row as expected with the BooksBorrowed column. All of my other ResultSet while loops have worked and returned rows with other SQL statements, it's just this one that doesn't and I don't know why.

   public void borrowBooks(String fName, String lName, Scanner input) throws SQLException {
        //first find out how many books the user has already borrowed
        int booksBorrowed = 0;
        int membID = 1; //this will be used for later
        sql = "select *, Count(MemberID) AS BooksBorrowed\r\n" +
                "FROM Book\r\n" + 
                "   JOIN AuthorIds USING (BookID)\r\n" + 
                "   JOIN Author USING (AuthorID)\r\n" + 
                "   JOIN Patron USING (MemberID)\r\n" + 
                "WHERE PatronFirstName LIKE ? AND PatronLastName LIKE ?\r\n" + 
                "GROUP BY MemberID\r\n" + 
                "ORDER BY BookID ASC";
        PreparedStatement stmt = connection.prepareStatement( sql );
        stmt.setString(1, fName);
        stmt.setString(2, lName);
        ResultSet res = stmt.executeQuery();
        while(res.next()) {
            booksBorrowed = res.getInt("BooksBorrowed");
            System.out.println(res.getInt("MemberID"));
            System.out.println("Test");
            membID = res.getInt("MemberID");
        }
        if(booksBorrowed >= 2) {
            System.out.println("You have already borrowed the maximum amount of 2 books. Return books to borrow more");
        }

Solution

  • I figured it out and it was that I should have gotten the memberID in a separate query because I was trying to change it to the corresponding patron in the same query as I was trying to get the number of books borrowed. The problem was that if the patron didn't have any books borrowed, then the result set would be empty and the memberID wouldn't change from what it was temporarily initialized as. This memberID was later inserted into the table for when a book was borrowed so it would be the temporary stand in each time and not the actual memberID of the patron, so the patron would have no books under their name as borrowed.