-1

嗨!我正在开发我的 Java MySql 应用程序,我需要将存储在我的数据库中的膳食数据保存在服务器上,以便稍后在组合框中显示它。用户将在组合框中选择他想要的餐点,当他按下“确认”按钮时,它将执行关于他的订单的查询。所以基本上,我的服务器数据库表中的每一餐(行)由 id_category (id_kategorija)、id_meal (id_jela)、name_of_meal (naziv_jela) 组成。我应该为此使用 HashMap 吗?如果可以的话,如何将所有数据保存在一个 HashMap 中,以便以后可以使用该 HashMap 轻松进行查询?

这是我的膳食数据库表的图片:

在此处输入图像描述

这是我的代码:

String queryZaJela;
Map <Integer,String>PopisJela = new HashMap<Integer, String>();
try {

        queryZaJela="SELECT id_kategorija, naziv_hrane FROM `naziv_jela`";

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://"
                + "localhost:3306/room_service", "root", "");
        Statement Stat = (Statement) con.createStatement();
        ResultSet Rez = Stat.executeQuery(queryZaJela);

        while (Rez.next()) { 

            PopisJela.put(Rez.getInt("id_kategorija"), Rez.getString("naziv_hrane") );
        } 
        PopisJela.put(0,"Select");

            Rez.close();
            Stat.close();
            con.close();

    } catch (Exception e) {
        System.out.println(e);
    }
4

1 回答 1

0

我可以建议你有一个小类来保存数据库中的所有 3 个值,并在将来根据你的查询将对象放入该类id_jela中。id_kategorija

public class mealStruct {
  public int id_kategorija;
  public int id_jela;
  public string naziv_hrane;
}

当您从数据库中读取数据时,为 mealStruct 类创建一个对象,并根据您需要的 id 将其放入地图中。

//here is the HashMap of id_kategorija/id_jela and mealStruct. 
//Keep filling hashMap with id and the object. when the user selects a meal from combo,
//get the id and access the object from mealStruct and get all 3 values to use in query.
<Integer,String>PopisJela = new HashMap<Integer, mealStruct>();
于 2013-08-21T08:08:41.917 回答