Why is the resultSet.getInt (1); necessary in the following code?

Viewed 5204

As far as I know getInt(column index)retrieves a column value from the current row, but I don't understand its purpose in a situation like this. Doesn't the SQL statement SELECT COUNT(*) FROM Gyujtoallomasok already count the rows in the table? If so, why do we need the rest?

public int count() {
    try (Connection connection = DriverManager.getConnection(URL);
         Statement statement = connection.createStatement()) {

        ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) FROM Gyujtoallomasok");
        if (resultSet.next()) {
            int count = resultSet.getInt(1);
            return count;
        }
    } catch (SQLException exception) {
        // TODO: log
    }
    return -1;
}
2 Answers

The method executeQuery() returns a ResultSet object and not an integer value.
The statement:

SELECT COUNT(*) FROM Gyujtoallomasok

counts the rows in the table and returns this result in the unnamed column COUNT(*).
To get this result you must extract it from the ResultSet object with the method getInt(), since the result is an integer, by passing the index 1 of the column (it is the 1st and only column in the ResultSet):

resultSet.getInt(1)

If you aliased the column like this:

SELECT COUNT(*) AS counter FROM Gyujtoallomasok

you could also get its value with:

resultSet.getInt("counter")

getInt is still needed since this line:

ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) FROM Gyujtoallomasok");

is placing what is returned from the database into a ResultSet which is "A table of data representing a database result set".

You then must iterate through the ResultSet to retrieve your answer which is what resultSet.next() and resultSet.getInt(); are doing.

Related