代码:
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
//执行select
private List<Map<String, Object>> executeGet(String schema, String sql) throws SQLException {
Statement statement = null;
ResultSet resultSet = null;
try {
Connection connection = getConnection();
connection.setCatalog(schema);
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
List<Map<String, Object>> resultList = new ArrayList<>();
while (resultSet.next()) {
Map<String, Object> dataMap = new HashMap<>();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
dataMap.put(metaData.getColumnLabel(i), resultSet.getObject(i));
} resultList.add(dataMap);
}
return resultList;
} catch (Exception e) {
throw e;
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
}
}
}
//执行update,insert,delete
private int executeUpdate(String schema, String sql) throws SQLException {
Statement statement = null;
try {
Connection connection = getConnection();
connection.setCatalog(schema);
statement = connection.createStatement();
return statement.executeUpdate(sql);
} catch (Exception e) {
throw e;
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
}
}
}
//将结果集转换为对象
public static <T> List<T> parserDbo(List<Map<String, Object>> dboMapList, Class<T> dboClass, boolean canEmpty) throws Exception {
if (CollectionUtil.isEmpty(dboMapList)) {
if (!canEmpty) {
throw new Exception("");
}
dboMapList = new ArrayList<>();
}
List<T> resultList = new ArrayList<>();
for (Map<String, Object> dboMap : dboMapList) {
resultList.add(BeanUtil.mapToBean(dboMap, dboClass, false));
}
return resultList;
}
}
注意:BeanUtil.mapToBean这个方法,需要导入以下依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.4</version>
</dependency>
本文档展示了如何使用Java进行SQL查询(包括SELECT, UPDATE, INSERT, DELETE),并介绍如何将ResultSet转换为对象实例。重点讲解了使用PreparedStatement和连接数据库的方法,以及Hutool工具库在数据映射过程中的应用。
735

被折叠的 条评论
为什么被折叠?



