位置:首頁 > Java技術 > java實例教學 > Java JDBC表的內容排序

Java JDBC表的內容排序

如何將一個表中的內容進行排序?

解決方法

下麵的示例使用Order by 的SQL命令來對表進行排序。

import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) throws Exception{
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection
      ("jdbc:derby://localhost:1527/testDb","name","pass");
      Statement stmt = con.createStatement();
      String query = "select * from emp order by name";
      String query1="select * from emp order by name, job";
      ResultSet rs = stmt.executeQuery(query);
      System.out.println("Table contents sorted by Name");
      System.out.println("Id Name    Job");
      while (rs.next()) {
         int id = rs.getInt("id");
         String name = rs.getString("name");
         String job = rs.getString("job");
         System.out.println(id + "  " + name+"   "+job);
      }
      rs = stmt.executeQuery(query1);
      System.out.println("Table contents after sorted
      by Name & job");
      System.out.println("Id Name    Job");
      while (rs.next()) {
         int id = rs.getInt("id");
         String name = rs.getString("name");
         String job = rs.getString("job");
         System.out.println(id + "  " + name+"   "+job);
      }
   }
}

結果

上麵的代碼示例將產生以下結果。該結果可能會不同。

Table contents after sorting by Name
Id Name    Job
1  ravi   trainee
5  ravi   MD
4  ravi   CEO
2  ravindra   CEO
2  ravish   trainee
Table contents after sorting by Name & job
Id Name    Job
4  ravi   CEO
5  ravi   MD
1  ravi   trainee
2  ravindra   CEO
2  ravish   trainee