public static void update(String sql, Object... args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = getConnection();
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
releaseDB(null, preparedStatement, connection);
}
}
// 查询一行记录
public <T> T getMessage(Class<T> clazz, String sql, Object... args) {
List<T> result = getMessages(clazz, sql, args);
if (result.size() > 0) {
return result.get(0);
}
return null;
}
// 查询多行记录
public <T> List<T> getMessages(Class<T> clazz, String sql, Object... args) {
List<T> list = new ArrayList<>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = getConnection();
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
resultSet = preparedStatement.executeQuery();
List<Map<String, Object>> values = resultSetToMapList(resultSet);// 调用下面的方法
list = mapListToBeanList(clazz, values);// 调用下面的方法
} catch (Exception e) {
e.printStackTrace();
} finally {
releaseDB(resultSet, preparedStatement, connection);
}
return list;
}
public List<Map<String, Object>> resultSetToMapList(ResultSet resultSet)
throws SQLException {
List<Map<String, Object>> values = new ArrayList<>();
Map<String, Object> map = null;
List<String> columnLabels = getColumnLabels(resultSet);
while (resultSet.next()) {
map = new HashMap<>();
for (String columnLabel : columnLabels) {
Object value = resultSet.getObject(columnLabel);
map.put(columnLabel, value);
}
values.add(map);
}
return values;
}
private List<String> getColumnLabels(ResultSet resultSet)
throws SQLException {
List<String> labels = new ArrayList<>();
ResultSetMetaData rsmd = resultSet.getMetaData();
for (int i = 0; i < rsmd.getColumnCount(); i++) {
labels.add(rsmd.getColumnLabel(i + 1));
}
return labels;
}
private <T> List<T> mapListToBeanList(Class<T> clazz,
List<Map<String, Object>> values) throws InstantiationException,
IllegalAccessException, InvocationTargetException {
List<T> result = new ArrayList<>();
T bean = null;
if (values.size() > 0) {
for (Map<String, Object> map : values) {
bean = clazz.newInstance();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String propertyName = entry.getKey();
Object value = entry.getValue();
BeanUtils.setProperty(bean, propertyName, value);
}
result.add(bean);
}
}
return result;
}
热门评论
@Test public void getStudents() { String sql = "select * from student"; List students = getMessages(Student.class, sql); System.out.println(students); }