简体   繁体   中英

How to get only the first row from a ResultSet

How do I get only the first row from a ResultSet ? I know how to iterate through the entire set, but how do I get just the first row?

Instead of iterating over the result set, just check if there exists an entry an read it:

ResultSet r = ...;
if(r.next()) {
  String s = r.getString(1);
  ...
}

Don't call resultSet.next(); simply extract the data,

A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

Alternatively You can also call first()

Moves the cursor to the first row in this ResultSet object.


In my case the following approach works well:

ResultSet RSet  = ...;
RSet.next();
Integer TestType = RSet.getInt("Type");

You can use absolute to navigate to the first row:

ResultSet rs = ...;
rs.absolute(1); // Navigate to first row
int id = rs.getInt("id");
...
//Code to get first row or first field of multiple rows
Class.forName("oracle.jdbc.driver.OracleDriver");
//Establish connection
con = DriverManager.getConnection(sConnString, sUserName, sPassword);
//Create statement.
statement = con.createStatement();
sQueryToExecute = "select field_Name from Table_Name where condition order by desc";
System.out.println(sQueryToExecute);
ResultSet rs = statement.executeQuery(sQueryToExecute);
while(rs.next())
{
    stringToStoreValue = rs.getString(1);
    break;
}

For those who seek an answer for Sqlite - Android, Here is my approach.

 if(RS.moveToNext()){
     String s = RS.getString(1);
     ... 
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM