【问题标题】:Fetch the data from database using the same column of same table using hash map使用哈希映射使用同一表的同一列从数据库中获取数据
【发布时间】:2015-07-18 05:31:48
【问题描述】:

我想使用 hashmap 从数据库中获取数据。

示例- 表名菜单

Restaurant_ID Item_Name Price Category
    1101        Burger    59    A
    1101        pizza     101   A
    1101        colddrink  40   B
    1101        bread      30   B

输出一定是这样的

A 类

Item_name      Price
Burger          59
Pizza           101

B 类

Item_name      Price
colddrink       40
bread           30

我想从表 MENU 中获取这样的数据到我的 jsp 页面。

请帮帮我。 我已经尝试了这么多,但我没有得到我需要的输出。

【问题讨论】:

  • 请分享您已经尝试过的内容
  • 你在这里给出了 2 个输出。您希望它们都来自同一个查询,还是您也可以接受多个查询?
  • 可以多次查询

标签: sql oracle jsp hashmap


【解决方案1】:

我在这里使用了ArrayList,但它会提供与您的代码相同的输出:

第1步:将Table_Name_Menu表中的所有类别放入ArrayList

public static ArrayList<Characters> getCategories(Connection con) throws SQLException {

    Statement stmt = null;
    String query =
        "select distinct(Category) from Table_Name_Menu order by Category ASC";

    stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(query);
    ArrayList<Character> categories = new ArrayList<Character>();

    while (rs.next()) {
        char category = rs.getString("Category").charAt(0);
        categories.add(category);
    }
    //This way, all the categories will come in categories Arraylist

    stmt.close();
    return categories;
}

注意:这是一个未编译的代码。请相应地放置 Try 和 Catch 块。

第 2 步:遍历您的 categories ArrayList 并为每个类别准备一个新查询,该查询将获取与该特定 Category 对应的所有内容

for(Iterator<Character> i = category.iterator(); i.hasNext(); ) {
    Statement stmt = null;
    stmt = con.createStatement();

    char newCategory = i.next();
    String query2 = "select Item_name, Price from Table_Name_Menu where Category = \"" +  newCategory + "\"";
    ResultSet rs = stmt.executeQuery(query2);

    //This prints the contents of the new Category
    System.out.println("Category : " + newCategory):
    while(rs.next()){
        System.out.println(rs.getString(1)); //Item Name
        System.out.println(rs.getString(2)); //Item Price
    }
    stmt.close();

    System.out.println("\n\n"); //Gap Between categories
}

这样您将获得与特定类别对应的所有内容。

【讨论】:

  • 如果这不是您想要的,请说明您的需求,我会相应地修改答案。
猜你喜欢
  • 1970-01-01
  • 2015-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-07
  • 2020-07-01
  • 2019-03-19
  • 2018-07-04
相关资源
最近更新 更多