Meaningless Drivel is fun!*
The moose likes JDBC and the fly likes ResultSet: I want a conditional output before iterating through it. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "ResultSet: I want a conditional output before iterating through it." Watch "ResultSet: I want a conditional output before iterating through it." New topic
Author

ResultSet: I want a conditional output before iterating through it.

Mark Lau
Ranch Hand

Joined: Dec 15, 2001
Posts: 120
I have

out.println("This is the search result.");

before I iterate through the ResultSet rs like so:

while(rs.next())
{ ...
}

But then this line: out.println("This is the search result."); will be executed even when no results are returned. This is certainly not very nice.

Too bad that ResulstSet rs=statement.executeQuery(query) never gets a null value, so says the documentation. This means that I can't do

if(rs != null)
{ out.println("This is the search result.");
}

Even worse, I surely can't put that line inside the while loop, like so:

while(rs.next())
{ out.println("This is the search result.");
.......
}

Actually, the following code works:

if(rs.next())
{ out.println("This is the search result.");
}

But, then I'll always miss one row down in the while loop (because the cursor has been moved down one row in the if statement).

I tried

rs.beforeFirst();

after the if block, hoping to move the cursor back one row. It did not work out right.

Understand my problem? Any smart way to handle this?
Thanks.
Gene
Napa Sreedhar
Ranch Hand

Joined: Jan 29, 2002
Posts: 62
boolean flag = true;
while(rs.next())
{
if (flag == true)
{
out.println("This is the search result.");
}
flag = false;
.......
}
I hope this helps.
Napa
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: ResultSet: I want a conditional output before iterating through it.
 
Similar Threads
How do you check is Result set is null
Result Set
Java Result Set
SQLException : Invalid cursor state
problem while retrieving one row & column from resultset Object