开发者

JDBC ResultSet behaving strangely

开发者 https://www.devze.com 2023-03-29 01:53 出处:网络
I am hitting my database and getting a ResultSet that tells me the current row # is 2 with a call to getRow(), but that fails to loop when I call the next() method:

I am hitting my database and getting a ResultSet that tells me the current row # is 2 with a call to getRow(), but that fails to loop when I call the next() method:

// Doesn't even loop once; fails on initial next() call -- entire loop skipped
try
{
    ResultSet oResults = executeSQL("SELECT * FROM widgets");

    // Returns a value of 2
    int iRowCount = oResults.getRow();

    if(iRowCount == 0)
        return;

    while(oResults.next())
    {
        // Never gets executed
    }

    // This gets executed though, and all the way down...
    // ...
}
catch(Exception e) { handleException(e); }

I've spent nearly an hour this morning trying to figure out what's happening, but this is the litera开发者_高级运维l code that I am trying to execute (it's a test/sandbox project, so it might not make logical sense). This ever happen to anybody?


The standard JDBC libraries return a ResultSet that has no clue as to how many rows are in it. Unless your implementation of executeSQL returns a CachedRowSet (which essentially has pre-scrolled through the result set and loaded all rows into memory), you'll never know the number of rows until you hit the end when oResults.next() returns false.

Thus your attempt at controlling program flow by checking the row count will never work.

Next, your call to ResultSet.getRow() is also probably useless. Here's what the javadoc says:

Retrieves the current row number. The first row is number 1, the second number 2, and so on.
Note: Support for the getRow method is optional for ResultSets with a result set type of TYPE_FORWARD_ONLY

Most implementations from JDBC drivers are forward only (ie you can't scroll backwards via the previous() method), so the result of getRow() is probably not useful.

Here's what your code should look like:

ResultSet oResults = executeSQL("SELECT * FROM widgets");

while(oResults.next())
{
    // Process rows
}

If you are still not getting into the while loop, it means your query is returning no rows - there's no other explanation. If getting no rows is "impossible", then I suggest you check your connection parameters to make sure you're connecting to the correct database (and not to localhost for example).


The method getRow() lets you check the number of the row where the cursor is currently positioned, so the call to next() is out of range of your results set. Try setting oResults.absolute(0); after you set iRowCount.

0

精彩评论

暂无评论...
验证码 换一张
取 消