Java中连接数据库查询使用Arrays.sort数组排序得匿名内部类对相同得查询语句进行封装使用list集合
时间: 2023-12-10 08:39:19 浏览: 74
JAVA 连接数据库 与数据库相关的各种操作 方法 封装
5星 · 资源好评率100%
以下是Java中连接数据库查询使用Arrays.sort数组排序得匿名内部类对相同得查询语句进行封装使用list集合的示例代码:
```java
import java.sql.*;
import java.util.*;
public class DatabaseQuery {
private Connection conn;
private PreparedStatement pstmt;
public DatabaseQuery() {
// 连接数据库
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "password";
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public List<Map<String, Object>> executeQuery(String sql, Object[] params) throws SQLException {
List<Map<String, Object>> list = new ArrayList<>();
pstmt = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i + 1, params[i]);
}
}
ResultSet rs = pstmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
while (rs.next()) {
Map<String, Object> map = new HashMap<>();
for (int i = 1; i <= columnCount; i++) {
map.put(rsmd.getColumnName(i), rs.getObject(i));
}
list.add(map);
}
rs.close();
pstmt.close();
return list;
}
public List<Map<String, Object>> executeQuery(String sql, Object[] params, String[] orderColumns) throws SQLException {
List<Map<String, Object>> list = executeQuery(sql, params);
if (orderColumns != null) {
Arrays.sort(orderColumns, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
});
list.sort(new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
for (String column : orderColumns) {
Object value1 = o1.get(column);
Object value2 = o2.get(column);
if (value1 == null && value2 == null) {
continue;
} else if (value1 == null) {
return -1;
} else if (value2 == null) {
return 1;
} else {
int compareResult = ((Comparable) value1).compareTo(value2);
if (compareResult != 0) {
return compareResult;
}
}
}
return 0;
}
});
}
return list;
}
public void close() throws SQLException {
conn.close();
}
public static void main(String[] args) throws SQLException {
DatabaseQuery dbQuery = new DatabaseQuery();
String sql = "SELECT * FROM table_name WHERE column1=? AND column2=?";
Object[] params = {value1, value2};
String[] orderColumns = {"column1", "column2"};
List<Map<String, Object>> list = dbQuery.executeQuery(sql, params, orderColumns);
for (Map<String, Object> map : list) {
System.out.println(map);
}
dbQuery.close();
}
}
```
在该示例代码中,`DatabaseQuery` 类封装了对数据库的查询操作。`executeQuery` 方法可以执行一条查询语句并返回一个包含多个 `Map` 对象的 `List`,每个 `Map` 对象表示一行查询结果,键为列名,值为列值。如果需要对结果进行排序,可以在调用 `executeQuery` 方法时传入 `orderColumns` 参数,该参数为一个 `String` 数组,表示需要按照哪些列进行排序。在该示例代码中,使用了匿名内部类对 `orderColumns` 数组进行排序,然后再对查询结果进行排序。
阅读全文