使用散列映射使用相同 table 的相同列从数据库中获取数据

Fetch the data from database using the same column of same table using hash map

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

例子- Table 名称菜单

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

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

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

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

第 1 步:将 Table_Name_Menu table 中的所有类别放入 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
}

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