Reputation: 49
I am executing a Statement query and storing the data in ResultSet rs.
// if no record is returned by the query
if (!rs.next() ) {
Step1
}
// if atleast one record is returned by the query
if(rs.next()){
do {
if (rs.getString(1).equalsIgnoreCase("0")){
Step2
}
if (rs.getString(1).equalsIgnoreCase("1")){
Step3
}
} while (rs.next());
}
However if i am getting only a single record from the query then no steps are executed. It would be of great help if anyone can point out the mistake.
Upvotes: 2
Views: 96
Reputation: 97
You should not call rs.next()
method twice. Following logic should work:
if (!rs.next() ) {
Step1
}
else{ // if atleast one record is returned by the query
do {
if (rs.getString(1).equalsIgnoreCase("0")){
Step2
}
if (rs.getString(1).equalsIgnoreCase("1")){
Step3
}
}while (rs.next());
}
Upvotes: 2
Reputation: 121998
You have to understand what exactly next()
method do. next() moves the cursor to next element. When you write next()
inside if there the condition passed and there are no more elements when it comes to while
.
And why don't you simplify your code by just doing
while ( rs.next() ) {
if (rs.getString(1).equalsIgnoreCase("0")){
Step2
}
if (rs.getString(1).equalsIgnoreCase("1")){
Step3
}
}
If you enter into while loop, there are items, otherwise No.
Upvotes: 5
Reputation: 1493
You are always skipping first element because you are calling .next()
twice before taking an element.
Try doing something like this:
if (rs.next()) {
// At least one record returned
do {
if (rs.getString(1).equalsIgnoreCase("0")) {
// Step2
}
if (rs.getString(1).equalsIgnoreCase("1")) {
// Step3
}
} while (rs.next());
} else {
// No records returned
}
Upvotes: 3
Reputation: 2503
Initially rs
contains one record or more precisely points to result set having one record.
Now when if(!rs.next())
is called then rs moves to the next record in result set which is not there as you have only one record. So this if goes well. But again when you use if(rs.next())
then rs
won't be having any record, hence the if
won't execute.
Upvotes: 2
Reputation: 3072
From JavaDoc ResultSet:
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
In your code you don't need second invocation of rs.next()
because cursor already on first row.
Upvotes: 2