jdbc 查询直接返回对应对象
public <T> List<T> list(Class<T> classt, String sql, Object... args) {
PreparedStatement statement = null;
ResultSet rs = null;
try {
List<T> lists = new ArrayList<T>();
statement = connection.prepareStatement(sql);
if(null != args){
for (int j = 0; j < args.length; j++) {
statement.setObject(j+1, args[j]);
}
}
rs = statement.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
Map<String, Object> row = new HashMap<String, Object>();
for (int i = 0; i < rsmd.getColumnCount(); i++) {
String columLabel = rsmd.getColumnLabel(i+1);
Object val = rs.getObject(columLabel);
row.put(StringUtil.convertHump(columLabel), val);
}
lists.add(SysContext.mapToObject(row,classt));
}
return lists;
} catch (SQLException e) {
e.printStackTrace();
throw new BaseException("执行SQL异常:" + e.getMessage());
}catch (Exception e) {
e.printStackTrace();
throw new BaseException("SQL查询封装异常:" + e.getMessage());
} finally {
try {
if (null != rs) {
rs.close();
rs = null;
}
if (null != statement) {
statement.close();
statement = null;
}
} catch (Exception e) {
}
}
}
评论区