JDBC - 数据排序



本章提供了一个使用 JDBC 应用程序对表中的记录进行排序的示例。它将使用ascdesc关键字对记录进行升序或降序排序。在执行以下示例之前,请确保您已准备好以下内容:-

  • 要执行以下示例,您可以将用户名密码替换为您实际的用户名和密码。

  • 您的 MySQL 或您正在使用的任何数据库都已启动并正在运行。

必要步骤

使用 JDBC 应用程序创建新数据库需要以下步骤:-

  • 导入包 - 需要包含用于数据库编程的 JDBC 类所在的包。大多数情况下,使用import java.sql.*就足够了。

  • 打开连接 - 需要使用DriverManager.getConnection()方法创建一个 Connection 对象,该对象表示与数据库服务器的物理连接。

  • 执行查询 - 需要使用 Statement 类型的对象来构建和提交 SQL 语句以对表中的记录进行排序。这些查询利用ascdesc子句对数据进行升序和降序排序。

  • 清理环境 - try with resources 自动关闭资源。

示例:对表的记录进行排序

在此示例中,我们有四个静态字符串,分别包含数据库连接 URL、用户名、密码和 SELECT 查询。现在使用 DriverManager.getConnection() 方法,我们准备了一个数据库连接。连接准备就绪后,我们使用 createStatement() 方法准备了一个 Statement 对象。下一步,我们准备并执行了对 REGISTRATION 表的 SELECT 查询,方法是调用 statement.executeQuery() 方法,在该方法中我们添加了对姓名的升序排序 Order By 子句。然后使用 executeQuery(),所有记录都被获取并存储在 ResultSet 对象中。迭代 ResultSet 并打印所有记录。

下一步,我们准备并执行了对 REGISTRATION 表的 SELECT 查询,方法是调用 statement.executeQuery() 方法,在该方法中我们添加了对姓名的降序排序 Order By 子句。然后使用 executeQuery(),所有记录都被获取并存储在 ResultSet 对象中。迭代 ResultSet 并打印所有记录。

将以下示例复制并粘贴到 JDBCExample.java 中,编译并运行如下:-

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCExample {
   static final String DB_URL = "jdbc:mysql://127.0.0.1/TUTORIALSPOINT";
   static final String USER = "guest";
   static final String PASS = "guest123";
   static final String QUERY = "SELECT id, first, last, age FROM Registration";

   public static void main(String[] args) {
      // Open a connection
      try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
         Statement stmt = conn.createStatement();) {		      
         System.out.println("Fetching records in ascending order...");
         ResultSet rs = stmt.executeQuery(QUERY + " ORDER BY first ASC");
         while(rs.next()){
            //Display values
            System.out.print("ID: " + rs.getInt("id"));
            System.out.print(", Age: " + rs.getInt("age"));
            System.out.print(", First: " + rs.getString("first"));
            System.out.println(", Last: " + rs.getString("last"));
         }

         System.out.println("Fetching records in descending order...");
         rs = stmt.executeQuery(QUERY + " ORDER BY first DESC");
         while(rs.next()){
            //Display values
            System.out.print("ID: " + rs.getInt("id"));
            System.out.print(", Age: " + rs.getInt("age"));
            System.out.print(", First: " + rs.getString("first"));
            System.out.println(", Last: " + rs.getString("last"));
         }
         rs.close();
      } catch (SQLException e) {
         e.printStackTrace();
      } 
   }
}

现在让我们编译以上示例,如下所示:-

C:\>javac JDBCExample.java
C:\>

当您运行JDBCExample时,它会产生以下结果:-

C:\>java JDBCExample
Fetching records in ascending order...
ID: 103, Age: 28, First: Sumit, Last: Mittal
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 100, Age: 30, First: Zara, Last: Ali
Fetching records in descending order...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>

示例:对表的记录基于两列进行排序

在此示例中,我们有三个静态字符串,分别包含数据库连接 URL、用户名和密码。现在使用 DriverManager.getConnection() 方法,我们准备了一个数据库连接。连接准备就绪后,我们使用 createStatement() 方法准备了一个 Statement 对象。下一步,我们准备并执行了对 EMPLOYEES 表的 SELECT 查询,方法是调用 statement.executeQuery() 方法,在该方法中我们添加了对 id 和 age 的升序排序 Order By 子句。然后使用 executeQuery(),所有记录都被获取并存储在 ResultSet 对象中。迭代 ResultSet 并打印所有记录。

将以下示例复制并粘贴到 JDBCExample.java 中,编译并运行如下:-

import java.sql.*;

// This class demonstrates use ORDER BY with 2 columns.
public class JDBCExample {

   static final String DB_URL = "jdbc:mysql://127.0.0.1/TUTORIALSPOINT";
   static final String USER = "root";
   static final String PASS = "guest123";

   public static void main(String args[]) {
      try{
         Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
         Statement stmt = conn.createStatement();
         String sel_qry = " select * from employees order by id, age ";
         ResultSet rs = stmt.executeQuery(sel_qry);
         System.out.println("Displaying records from EMPLOYEES table sorted by id, age" );
         System.out.println("-------------------------------------------------------");
         while(rs.next()){
            System.out.print(" ID: " + rs.getInt(1));
            System.out.print(", AGE: " + rs.getInt(2));
            System.out.print(", FirstName: " + rs.getString(3));
            System.out.println(", LastName: " + rs.getString(4));
         }
         System.out.println("--------------------------------------------");
         rs.close();
         stmt.close();
         conn.close();
      }catch(SQLException e){
         e.printStackTrace();
      }
   }
}

现在让我们编译以上示例,如下所示:-

C:\>javac JDBCExample.java
C:\>

当您运行JDBCExample时,它会产生以下结果:-

C:\>java JDBCExample
Displaying records from EMPLOYEES table sorted by id, age
-------------------------------------------------------
 ID: 1, AGE: 50, FirstName: Shahbaz, LastName: Ali
 ID: 2, AGE: 25, FirstName: Mahnaz, LastName: Fatma
 ID: 4, AGE: 28, FirstName: Sumit, LastName: Mittal
 ID: 21, AGE: 35, FirstName: Jeevan, LastName: Rao
 ID: 22, AGE: 40, FirstName: Dinesh, LastName: Kumar
 ID: 25, AGE: 35, FirstName: Jeevan, LastName: Rao
 ID: 26, AGE: 35, FirstName: Aditya, LastName: Chaube
 ID: 34, AGE: 45, FirstName: Ahmed, LastName: Ali
 ID: 35, AGE: 51, FirstName: Raksha, LastName: Agarwal
--------------------------------------------

C:\>

示例:对表的记录进行升序和降序排序

在此示例中,我们有三个静态字符串,分别包含数据库连接 URL、用户名和密码。现在使用 DriverManager.getConnection() 方法,我们准备了一个数据库连接。连接准备就绪后,我们使用 createStatement() 方法准备了一个 Statement 对象。下一步,我们准备并执行了对 EMPLOYEES 表的 SELECT 查询,方法是调用 statement.executeQuery() 方法,在该方法中我们添加了对 age 的升序排序和对姓氏的降序排序 Order By 子句。然后使用 executeQuery(),所有记录都被获取并存储在 ResultSet 对象中。迭代 ResultSet 并打印所有记录。

将以下示例复制并粘贴到 JDBCExample.java 中,编译并运行如下:-

import java.sql.*;

// This class demonstrates ORDER BY 2 columns one ASC, one DESC
public class JDBCExample {

   static final String DB_URL = "jdbc:mysql://127.0.0.1/TUTORIALSPOINT";
   static final String USER = "root";
   static final String PASS = "guest123";

   public static void main(String args[]) {
      try{
         Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
         Statement stmt = conn.createStatement();
         String sel_qry = " select * from employees order by age asc, last desc";
         ResultSet rs = stmt.executeQuery(sel_qry);
         System.out.println("Displaying records from EMPLOYEES table sorted by age(ASC) and last name (DESC)." );
         System.out.println("-------------------------------------------------------");
         while(rs.next()){
            System.out.print(" ID: " + rs.getInt(1));
            System.out.print(", AGE: " + rs.getInt(2));
            System.out.print(", FirstName: " + rs.getString(3));
            System.out.println(", LastName: " + rs.getString(4));
         }          
         System.out.println("--------------------------------------------");
         rs.close();
         stmt.close();
         conn.close();           
      }catch(SQLException e){
         e.printStackTrace();
      }
   }
}

现在让我们编译以上示例,如下所示:-

C:\>javac JDBCExample.java
C:\>

当您运行JDBCExample时,它会产生以下结果:-

C:\>java JDBCExample
Displaying records from EMPLOYEES table sorted by age(ASC) and last name (DESC).
-------------------------------------------------------
 ID: 2, AGE: 25, FirstName: Mahnaz, LastName: Fatma
 ID: 4, AGE: 28, FirstName: Sumit, LastName: Mittal
 ID: 21, AGE: 35, FirstName: Jeevan, LastName: Rao
 ID: 25, AGE: 35, FirstName: Jeevan, LastName: Rao
 ID: 26, AGE: 35, FirstName: Aditya, LastName: Chaube
 ID: 22, AGE: 40, FirstName: Dinesh, LastName: Kumar
 ID: 34, AGE: 45, FirstName: Ahmed, LastName: Ali
 ID: 1, AGE: 50, FirstName: Shahbaz, LastName: Ali
 ID: 35, AGE: 51, FirstName: Raksha, LastName: Agarwal
--------------------------------------------


C:\>
广告