5

i try to select from my table, only select the last row. I've tried this :

rset = s.executeQuery("select noorder from orders");
rset.last();
String noorder = rset.getString("noorder");`

rset is resultset, and s is statement. But it throw an exception : ResultSet may only be accessed in a forward direction`

I've tried this to :

if (rset != null) {                
   while(rset.next()){
       rset.last();
   }
}

Am I doing wrong? Any idea? Thanks

Edit : This is the answer, as suggested by @Bhavik-Ambani (thanks for him). And this is my code :

        Statement s2 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
        rset = s2.executeQuery("select noorder from orders");
        rset.afterLast();
        GETLASTINSERTED:
        while(rset.previous()){
            noorder = rset.getString("noorder");
            break GETLASTINSERTED;//to read only the last row
        }

Hope it will be help another. Java rocks!

4

5 回答 5

5

A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row.

At code level you can do the following thing

Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet resultSet = statement.executeQuery("select noorder from orders");
resultSet.afterLast();
while (resultSet.previous()) {
  String productCode = resultSet.getString("col_one");
  String productName = resultSet.getString("col_two");

}
connection.close();
于 2012-05-18T20:15:40.917 回答
2

The isLast() should be what you're looking for.

ResultSet rs = stmt.executeQuery(query);

while(rs.next()) {
  if(rs.isLast()) {
      // is last row in ResultSet
  }
}
于 2018-11-12T00:39:36.413 回答
1

Remember to apply an order by clause otherwise the last entry in your ResultSet may not be what you expect.

于 2012-05-18T22:47:06.257 回答
1

You can use: connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

于 2020-11-18T19:51:13.723 回答
0
rset = s.executeQuery("SELECT * FROM table_name ORDER BY unique_column DESC LIMIT 1");

String noorder = rset.getString("noorder");`
于 2012-05-18T20:29:52.040 回答