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)方法。