在Java程序中使用Resultset [英] Using Resultset in Java Program
问题描述
Resultset rs=stmt.executeQuery("select count(*) from feedsca group by score order by score");
使用上面的Java代码,我从名为feedsCA的表中检索行数.
Using the above java code above, am retrieving the counts of rows from the table named feedsCA.
当尝试使用rs.getInt(1),rs.getInt(2),rs.getInt(3)检索计数时,我的错误如下所示,
While trying to retrieving the counts using rs.getInt(1),rs.getInt(2),rs.getInt(3), I end with an error saying as below,
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: The result set has no current row.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.verifyResultSetHasCurrentRow(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getterGetColumn(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getInt(Unknown Source)
at SimpleMail.main(SimpleMail.java:151)
更新:
上述异常已解决.
但是我得到以下异常,我不知道原因.请告知.
But I get the following exception, for which I dont know the reason. Please advise.
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.verifyValidColumnIndex(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getterGetColumn(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getInt(Unknown Source)
at SimpleMail.main(SimpleMail.java:152)
这是我更新程序的方式.为我找到一种合理的方式,因为我能很好地理解下面的循环无法按要求工作.
This is how I have updated my program. Find me a logical way as I can understand well that the loop below will not work as required.
rs=stmt.executeQuery("select count(*) from feedsca group by score order by score");
while(rs.next()){
pw.printf(rowFormat, rs.getLong(1),"0",rs.getLong(2),rs.getLong(3));}
推荐答案
您必须将结果集的光标移动到行-通过resultSet.first()
或resultSet.next()
.最初,光标指向第一行之前,因此是您的例外.
You have to move the cursor of the result set to a row - either by resultSet.first()
or by resultSet.next()
. Initially the cursor is pointing before the first row, hence your exception.
要迭代ResultSet
时:
while(rs.next()) {
...
}
更新:对于第二个问题-(如卡萨布兰卡所指出的),您的查询似乎只返回一列,而您要求的是第二列和第三列-均未找到.请注意,rs.getX(idx)
idx
中的是列,而不是行.
Update: For your second problem - (as noted by Casablanca) your query seems to return only one column, and you are asking for a 2nd and 3rd - and they are not found. Note that in rs.getX(idx)
idx
is the column, not the row.
这篇关于在Java程序中使用Resultset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!