You should use the next
statement first.
ResultSet set = statement.executeQuery();
if (set.next()) {
userName = set.getString(1);
//your logic...
}
UPDATE
As the Java 6 Documentation says
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.
This means when you execute the sentence
ResultSet set = statement.executeQuery();
The ResultSet set
will be created and pointing to a row before the first result of the data. You can look it this way:
SELECT email,firstname FROM registrationinformation
email | firstname
____________________________________
0 <= set points to here
1 email1@gmail.com | Email1 Person
2 foo@bar.com | Foo Bar
So, after openning your ResulSet, you execute the method next
to move it to the first row.
if(set.next())
Now set
looks like this.
email | firstname
____________________________________
0
1 email1@gmail.com | Email1 Person <= set points to here
2 foo@bar.com | Foo Bar
If you need to read all the data in the ResultSet, you should use a while instead of if:
while(set.next()) {
//read data from the actual row
//automatically will try to forward 1 row
}
If the set.next()
return false, it means that there was no row to read, so your while loop will end.
More information here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…