Java中连接数据库查询使用数组排序得匿名内部类对相同得查询语句进行封装
时间: 2023-12-10 12:39:14 浏览: 82
可以使用 Java 中的 JDBC API 连接数据库,并使用数组排序来对查询结果进行排序。以下是一个示例代码:
```java
import java.sql.*;
import java.util.*;
public class DatabaseSorter {
private Connection conn;
public DatabaseSorter(String url, String user, String password) throws SQLException {
conn = DriverManager.getConnection(url, user, password);
}
public List<Map<String, Object>> executeQuery(String sql, String[] orderColumns) throws SQLException {
List<Map<String, Object>> result = new ArrayList<>();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
ResultSet rs = stmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
while (rs.next()) {
Map<String, Object> row = new HashMap<>();
for (int i = 1; i <= colCount; i++) {
row.put(rsmd.getColumnName(i), rs.getObject(i));
}
result.add(row);
}
}
Collections.sort(result, new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> row1, Map<String, Object> row2) {
for (String col : orderColumns) {
Comparable val1 = (Comparable) row1.get(col);
Comparable val2 = (Comparable) row2.get(col);
int cmp = val1.compareTo(val2);
if (cmp != 0) {
return cmp;
}
}
return 0;
}
});
return result;
}
public void close() throws SQLException {
conn.close();
}
public static void main(String[] args) throws SQLException {
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "root";
DatabaseSorter sorter = new DatabaseSorter(url, user, password);
String sql = "SELECT * FROM employees";
String[] orderColumns = {"salary", "age"};
List<Map<String, Object>> result = sorter.executeQuery(sql, orderColumns);
for (Map<String, Object> row : result) {
System.out.println(row);
}
sorter.close();
}
}
```
在此示例中,我们使用 JDBC API 连接到 MySQL 数据库,并使用匿名内部类实现了一个 `Comparator` 接口来对查询结果进行排序。我们还使用了 `Map` 来表示每一行查询结果,并使用了 `List` 来存储整个查询结果。最终输出了按照 `salary` 和 `age` 字段进行排序后的查询结果。
阅读全文