简体   繁体   English

在多维HashMap中从MySQL查询存储多行

[英]Storing Multiple Rows from MySQL query in MultiDimensional HashMap

So I'm trying to store a MySQL query result set into a multi dimensional HashMap as listed so: 因此,我尝试将MySQL查询结果集存储到如下所示的多维HashMap中:

  public HashMap<String, HashMap<String, String>> getData(String query)
  {
     Statement stmt = null;
     HashMap<String, HashMap<String, String>> results = new HashMap<String, HashMap<String, String>>();

     try
     {
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        ResultSetMetaData rsmd = rs.getMetaData();

        while (rs.next())
        {
           for (int i = 1; i < rsmd.getColumnCount() + 1; i++)
           {
              results.put(Integer.toString(i - 1), new HashMap<String, String>());
              results.get(Integer.toString(i - 1)).put(rsmd.getColumnLabel(i), rs.getString(i));
           }
        }
     }
     catch (SQLException ex)
     {
        ex.printStackTrace(System.out);
     }

     return results;
  }

However when using the function to print it out as so: 但是,当使用该函数将其打印出来时:

   public static void printMap(Map mp)
   {
       Iterator it = mp.entrySet().iterator();

       while (it.hasNext())
       {
           Map.Entry pair = (Map.Entry)it.next();
           System.out.println(pair.getKey() + " = " + pair.getValue());
           it.remove();
       }
   }

It is only storing a single row result and I can't wrap my head around why. 它仅存储单行结果,我无法解释为什么。

0 = {Date=2014-11-04}
1 = {Num=1256}
2 = {ATime=null}
3 = {ALocCode=null}
4 = {DTime=1:00 PM}
5 = {DLocCode=JFK}
6 = {EstATime=8:00 PM}
7 = {EstDTime=1:00 PM}
8 = {EId=7624}

My question is, and the only way I can put it is relating to PHP, is how can I make it store like this? 我的问题是,并且我唯一可以说的与PHP有关的方法是,如何使它像这样存储?

$result[0]['Date'] = '3214';
....
$result[1]['Date'] = '6426';

Since that is essentially what I'm trying to achieve? 既然这实际上是我要实现的目标?

main problem that you've swapped "rows" and "columns", next one is that you're re-creating HashMap every time you put field, proper code will look like this: 您交换了“行”和“列”的主要问题,下一个是每次您输入字段时都在重新创建HashMap,正确的代码如下所示:

public Map<String, Map<String, String>> getData(final String query) {
    final Map<String, Map<String, String>> results = new HashMap<>();

    try (final Statement stmt = this.conn.createStatement(); final ResultSet rs = stmt.executeQuery(query);) {
        final ResultSetMetaData rsmd = rs.getMetaData();
        long rId = 0;
        while (rs.next()) {
            final Map<String, String> record = new HashMap<>();
            for (int i = 1; i < (rsmd.getColumnCount() + 1); i++) {
                record.put(rsmd.getColumnLabel(i), rs.getString(i));
            }
            results.put(String.valueOf(rId++), record);
        }
    } catch (final SQLException ex) {
        ex.printStackTrace(System.out);
    }

    return results;
}

public static void printMap(final Map<?, ?> mp) {
    for (final Entry<?, ?> entry : mp.entrySet()) {
        final Object key = entry.getKey();
        final Object value = entry.getValue();
        if (value instanceof Map) {
            System.out.println(key);
            printMap((Map<?, ?>) value);
        } else {
            System.out.println(key + "=" + entry.getValue());
        }
    }
}

The answer by Lashane is good for the errors you needed solving, however it can be improved: Lashane的答案非常适合您需要解决的错误,但是可以改进:

  • You wanted numeric access ( $result[0]['Date'] ) to the rows, not string. 您希望对行而不是字符串进行数字访问( $result[0]['Date'] )。
  • print method should use fully typed parameter. print方法应使用完全类型化的参数。
  • Rows should be stored in TreeMap or LinkedHashMap or ArrayList to retain row order. 行应存储在TreeMapLinkedHashMapArrayList以保留行顺序。 ArrayList is better for your case, actually. 实际上, ArrayList更适合您的情况。
  • Columns should be stored in LinkedHashMap to retain column order. 列应存储在LinkedHashMap以保留列顺序。
  • Do not catch exception and continue. 不要捕捉异常并继续。 Allow it to cascade up to caller. 允许它级联到呼叫者。

Updated version: 更新后的版本:

public List<Map<String, String>> getData(final String query) throws SQLException {
    final List<Map<String, String>> results = new ArrayList<>();
    try (Statement stmt = this.conn.createStatement();
         ResultSet rs = stmt.executeQuery(query)) {
        ResultSetMetaData metaData = rs.getMetaData();
        while (rs.next()) {
            Map<String, String> record = new LinkedHashMap<>();
            for (int col = 1; col <= metaData.getColumnCount(); col++)
                record.put(metaData.getColumnLabel(col), rs.getString(col));
            results.add(record);
        }
    }
    return results;
}

public static void printMap(List<Map<String, String>> rows) {
    for (int rowNum = 0; rowNum < rows.size(); rowNum++)
        System.out.println(rowNum + " = " + rows.get(rowNum));
}

You can now access it like you did in PHP: 您现在可以像在PHP中一样访问它:

// PHP (for reference, the way you requested)
$result[0]['Date']

// Java
result.get(0).get("Date")

// Groovy
result[0]['Date']
result[0].Date

// JSP
<c:forEach var="row" items="${result}" varStatus="rowStatus">
  ${rowStatus.index} = <c:out value="${row.Date}"/>, ...
</c:forEach>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM