JDBC连接数据库查询数据时时返回ResultSet结果集。ResultSet中存放键值对。我们可以首先取得Key值,然后通过key值获取我们想要的value。那么我们如何获取Key值呢?看下面代码:
try {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
rs = getStmt().executeQuery(sql);
// 得到结果集ResultSet的结构信息,比如字段数、字段名等
ResultSetMetaData rsmd = rs.getMetaData();
// 得到数据集的列数
int columncount = rsmd.getColumnCount();
while (rs.next()) {
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < columncount; i++) {
String key = rsmd.getColumnLabel(i+1);
//String key = rsmd.getColumnName(i + 1)
String value = rs.getString(key);
map.put(key, value);
}
list.add(map);
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
colse();
}
对于Sql Server和Oracle数据库我们可以用String key = rsmd.getColumnName(i + 1)来获取Key值,但是对于Mysql数据库,当我们使用聚合函数时如:select count(*) as stu_count from student,我们会发现这时取得的key值为空(''),要想取得key值就需要使用String key = rsmd.getColumnLabel(i + 1)方法。
转载于:https://blog.51cto.com/6883741/1410552