Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

java - Go to last row from result set in jdbc with sql server

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...