Thread: JDBC next() method

JDBC next() method

From
Jon Barnett
Date:
I'm not quite sure about the correct operation of the JDBC next() method.

Suppose I have the following code:

queryResult = dbStatement.executeQuery("select max(history_id) from history");
if (queryResult.next())
    nextID = queryResult.getLong(1) + 1;
else
    nextID = 0;

With the postgresql JDBC driver, the minimum value for nextID is 1, even if the
history table is empty.  I had expected that an empty result set would be
returned if the history table is empty (0 rows returned for the select), and
queryResult.next() would be false.  Is this an incorrect interpretation on my
part?

Thanks,

JonB.

Re: [INTERFACES] JDBC next() method

From
Herouth Maoz
Date:
At 15:57 +0300 on 14/04/1999, Jon Barnett wrote:


> I had expected that an empty result set would be
> returned if the history table is empty (0 rows returned for the select), and
> queryResult.next() would be false.  Is this an incorrect interpretation
>on my
> part?

It is. In PostgreSQL, when an aggregate function is used, it always returns
one row containing one field. If it had no values that matched the query,
that one field is NULL.

The result of an aggregate is never 0 rows. It is always one row (per group
if you used GROUP BY).

This is the reason why you have to check for a null field rather than for
the result of next(). You have to call next(), but you don't really have to
check its value, because it will be true once (and once only). You call it
merely to fetch the row. And then you get the value of the field thus
retrieved, and check it for null.

Herouth

--
Herouth Maoz, Internet developer.
Open University of Israel - Telem project
http://telem.openu.ac.il/~herutma