//通用的查询方法之四:查询多行多列,但每一行又不是一个JavaBean
/*
* SELECT did,AVG(salary),MAX(Salary) FROM t_employee GROUP BY did;
* did avg(salary) max(salary)
1 1990.90 8900
2 4889 6899
*/
public static List> getListMap(String sql,Object… args)throws Exception{
//2、获取连接
Connection conn = JDBCUtils.getConnection();
//3、对sql进行预编译
PreparedStatement pst = conn.prepareStatement(sql);
//4、对?进行设置值
if(args!=null && args.length>0){
for (int i = 0; i < args.length; i++) {
pst.setObject(i+1, args[i]);
}
}
//5、执行sql
ResultSet rs = pst.executeQuery();
//获取结果集的元数据对象
ResultSetMetaData metaData = rs.getMetaData();
//一共有几列
int count = metaData.getColumnCount();
//创建List
ArrayList> list = new ArrayList>();
while(rs.next()){
//每一行是一个Map的对象
HashMap map = new HashMap();
//map的key是列名
for (int i = 0; i < count; i++) {
//(1)获取列名或别名
String columnName = metaData.getColumnLabel(i+1);
//(2)获取对应的值
Object value = rs.getObject(i+1);
//(3)把这对值放到map中
map.put(columnName, value);
}
//把map放到List中
list.add(map);
}
//6、释放资源
JDBCUtils.closeQuietly(rs,pst,conn);
return list;
}