Java如何排序資料庫表的資料內容?

2019-10-16 22:26:00

在Java程式設計中,如何排序資料庫表的資料內容?假定資料庫名稱是:testdb,其中有一個表:employee,這個表中有4條記錄。

建立資料庫表的語句 -

use testdb;
create table if not exists employees (
  id int not null,
  age int not null,
  first varchar (255),
  last varchar (255)
);
INSERT INTO Employees VALUES (100, 28, 'Max', 'Su');
INSERT INTO Employees VALUES (101, 25, 'Wei', 'Wang');
INSERT INTO Employees VALUES (102, 30, 'Kida', 'Su');
INSERT INTO Employees VALUES (103, 28, 'Kobe', 'Bryant');

以下範例使用SQL命令的Order by對錶中的資料進行排序。

package com.yiibai;

import java.sql.*;

public class SortTableData {
    public static void main(String[] args) throws Exception {
        String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        String DB_URL = "jdbc:mysql://localhost/testdb?useSSL=false";
        String User = "root";
        String Passwd = "123456";
        try {
            Class.forName(JDBC_DRIVER);
        } catch (ClassNotFoundException e) {
            System.out.println("Class not found " + e);
        }
        Connection con = DriverManager.getConnection(DB_URL, User, Passwd);
        Statement stmt = con.createStatement();
        String query = "select * from employees order by first";
        String query1 = "select * from employees order by last, age";

        ResultSet rs = stmt.executeQuery(query);
        System.out.println("Table contents sorted by Name");
        System.out.println("Id Name age");

        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("first");
            String age = rs.getString("age");
            System.out.println(id + "  " + name + "   " + age);
        }
        rs = stmt.executeQuery(query1);
        System.out.println("Table contents after sorted by last & age");
        System.out.println("Id lastname    age");

        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("last");
            String age = rs.getString("age");
            System.out.println(id + "  " + name + "   " + age);
        }
    }
}

上述程式碼範例將產生以下結果。

Table contents sorted by Name
Id Name age
102  Kida   30
103  Kobe   28
100  Max   28
101  Wei   25
Table contents after sorted by last & age
Id lastname    age
103  Bryant   28
100  Su   28
102  Su   30
101  Wang   25

註:如果JDBC驅動程式安裝不正確,將獲得ClassNotfound異常。

Class not found java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
JDBC Class found
SQL exception occuredjava.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/testdb