您应该next
首先使用该语句。
ResultSet set = statement.executeQuery();
if (set.next()) {
userName = set.getString(1);
//your logic...
}
更新
正如Java 6文档所说
ResultSet游标最初位于第一行之前;第一个对方法的调用接下来使第一行成为当前行;第二个调用使第二行成为当前行,依此类推。
这意味着当您执行句子时
ResultSet set = statement.executeQuery();
set
将创建ResultSet 并指向数据第一个结果之前的行。您可以这样看:
email | firstname
____________________________________
0 <= set points to here
1 email1@gmail.com | Email1 Person
2 foo@bar.com | Foo Bar
因此,在打开ResulSet之后,您将执行next
将其移至第一行的方法。
if(set.next())
现在set
看起来像这样。
email | firstname
____________________________________
0
1 email1@gmail.com | Email1 Person <= set points to here
2 foo@bar.com | Foo Bar
如果需要读取ResultSet中的所有数据,则应使用一阵子而不是if:
while(set.next()) {
//read data from the actual row
//automatically will try to forward 1 row
}
如果set.next()
返回false,则意味着没有要读取的行,因此while循环将结束。
更多信息在这里。