日期:2014-05-20  浏览次数:20702 次

ResultSet的问题纠结,来讨论下
                int totalRecords=0;
Connection conn=DB.getConn();//  自己封装的DB
String sql="select count(*) from dnews";
Statement stmtCount = DB.getStatement(conn);
ResultSet rsCount = DB.getResultSet(stmtCount, sql);
try {
rsCount.next();
totalRecords = rsCount.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
}finally{
DB.close(rsCount);
DB.close(stmtCount);
DB.close(conn);
}
return totalRecords ;


问题:rsCount 在接受完结果集后的游标指在哪里, 为什么要写rsCount.next();
我将rsCount.next()换成rsCount.last(); 得到totalRecords的结果是一样的:
在rsCount.next()这句下将totalRecords = rsCount.getRow();则结果等于1;
为什么将rsCount.next()换成rsCount.last();totalRecords = rsCount.getRow();还等于1.
  我知道getRow()是得到行号,rsCount.getInt(1)是得到列的值, 
请具体讲讲吧

------解决方案--------------------
因为这里rsCount只有一行,所以next和last之后就是相同的,都是指向了第一行。你也就知道了,刚刚接收完数据后游标是在0的位置,你也就知道为什么要先写一下rsCount.next();
还有就是next和last返回的值都是boolean值,当指向的行不存在时就返回false,也就是说如果你再写一个rsCount.next();游标就指向了2,而现在没有第二行,也就返回false,而last是在没有结果的时候返回false
------解决方案--------------------
引用:
select count(*) from dnews
这个是关键

JDK doc描述
     * Moves the cursor froward one row from its current position.
     * A <code>ResultSet</code> cursor is initially positioned
     * before the first row; the first call to the method
     * <code>next</code> makes the first row the current row; the
     * second call makes the second row the current row, and so on. 
从当前游标位置向前移动一行,ResultSet游标初始化位置被置于第一行之前;第一次调用next方法使游标移动到第一行。
第一次调用将使游标移动到第二行,依次类推。

 /**
     * Moves the cursor to the last row in
     * this <code>ResultSet</code> object.
移动游标到ResultSet对象的最后一行

如果总数为1的话,第一行不就是最后一行吗