2016-04-18 4 views
0

データベーステーブルから最後の5つのエントリを選択します。私のデータベースに列ID(int)、製品(文字列)、バージョン(文字列)、説明(文字列)があります。DBテーブルから最後の5つのエントリを選択してページに表示したい。 JSPを使ってどうすれば実現できますか?

データベース内に50のエントリがあり、テーブルから選択した最後の5つのエントリ(つまり46,47,48,49および50)が必要であり、HTMLページにそれを表示する必要があります。 JSPを使ってどうすればいいですか?お時間を

<%@ page import="java.util.*" %> 
<%@ page import="java.sql.*" %> 
<%@ page import="java.text.*" %> 
<%@ page language = "java" %> 
<% 
    int id=0; 
Connection connect2=null; 
Statement state2=null; 
ResultSet result2=null; 
Connection connect=null; 
Statement state=null; 
ResultSet result=null; 
try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
    connect2=DriverManager.getConnection("jdbc:odbc:ppbu"); 
    state2 = connect2.createStatement();  
    String strQuery2 = "select MAX(ID) from kb_articles_list"; 
    result2 = state2.executeQuery(strQuery2); 
    while(result2.next()) 
    {id=result2.getInt(1); 
    } 
}finally { 
     try { 
      if (state2 != null) 
      state2.close(); 
     } catch (SQLException e) {} 
     try { 
      if (connect2 != null) 
      connect2.close(); 
     } catch (SQLException e) {} 
     } 

    out.print(id); 
    for(int a=0; a<5; a++) 
     {  
    try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
    connect=DriverManager.getConnection("jdbc:odbc:ppbu"); 
    state = connect.createStatement(); 
    String strQuery = "select * from kb_articles_list where ID.equals(id)"; 
    result = state.executeQuery(strQuery); 
    while(result.next()){ 
      %> 
      <option><%= result.getString(2)%></option> 
     <% }state.close(); connect.close(); %>   
    <% }catch (Exception e) { 
      e.printStackTrace();}  

     id--;}%> 
+0

リレーショナルデータベーステーブルは本質的に*注文されません。 SQLの 'ORDER BY'節を使用して結果セットを順序付けることができます。クライアントコードで、使用しているデータベースエンジンの適切なSQLを実行させるだけです。各エンジンには、5つのレコードのみを選択する別の方法があります。 –

+0

ありがとうございます。私は "注文"を試みたが、それは私のために働いていない。 TRYセクションで使用できるSQLクエリの1行の例を教えてください。 – Ashish

+0

'ORDER BY id DESC FETCH FIRST 5 ROWS ONLY'はANSI SQLの方法です。 (残念ながら、多くの製品にはここに独自の方法があります...) – jarlh

答えて

0

ありがとう:

は、以下の私のサンプルコードです。私は以下のコードを使ってこれを動作させました。

String strQuery = "select * from kb_articles_list where ID="+id+""; 
関連する問題