您应该
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 here1 email1@gmail.com | Email1 Person2 foo@bar.com | Foo Bar
因此,在打开ResulSet之后,您将执行
next将其移至第一行的方法。
if(set.next())
现在
set看起来像这样。
email | firstname ____________________________________01 email1@gmail.com | Email1 Person <= set points to here2 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循环将结束。
更多信息在这里。



