- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to sort contents of a table in Java
Problem Description
How to sort contents of a table?
Solution
Following example uses Order by SQL command to sort the table.
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);
}
}
}
Result
The above code sample will produce the following result. The result may vary.
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
java_jdbc.htm
Advertisements