Moving ResultSet to first

2019-06-14 08:32发布

问题:

I have a resultset obejct as rs and i used the fragment of code to count the number of rows..

       while(rs.next())
           count++;

and i has to use the same resultset again to retrieve the data. I used the method

    rs.beforefirst(); 

but it is not working... control is not entering into

   while(rs.next()){
      cid=rs.getInt(1);
      taskdate=rs.getString(2);
      tasktime=rs.getString(3);
      addr=rs.getString(4);
   }

I has to return 4 rows according to my query.. but it doesn't ???

回答1:

Resultset is the forward only . If you want to navigate back to the first record you need to create scrollable resultset .

  // Create a scrollable result set
Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY);
ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");

// Move cursor forward
while (resultSet.next()) {
  // Get data at cursor
  String s = resultSet.getString(1);
}

// Move cursor backward
while (resultSet.previous()) {
  // Get data at cursor
  String s = resultSet.getString(1);
}

// Move cursor before first record
resultSet.beforeFirst();  //required statement in this case 


回答2:

Check if the ResultSet is of type TYPE_FORWARD_ONLY - then the call to beforefirst wouldn't work (according to the docs it throws in this case).



标签: jsp oracle10g