下面的代码从数据库中获取我需要的信息,但并未打印出所有信息。首先,我知道它正在从表中获取所有正确的信息,因为我已经在sql developer中尝试了查询。

public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        conn = getConnection();
        String query = "SELECT menu.menu_id, menu_title, dish.dish_id, dish_name, dish_description, dish_price, menu.week_no "
                + "FROM menu, dish, menu_allocation "
                + "WHERE menu.active = '1' "
                + "AND menu.menu_id = menu_allocation.menu_id "
                + "AND dish.dish_id = menu_allocation.dish_id "
                + "AND menu.week_no IN (09, 10, 11)";
        stmt = conn.createStatement();

        rs = stmt.executeQuery(query);
        MenuList list = null;
        while (rs.next()) {
            list = new MenuList(rs);
            System.out.println(rs.getRow());
        }
        for (int pos = 0; pos < list.size(); pos++) {
            Menu menu = list.getMenuAt(pos);

            System.out.println(menu.getDescription());
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
        }
    }

}


终端的输出如下:

 3 //Number of rows
 Fish and Chips //3rd row
 Chocolate Cake //2nd row
 //Here should be 1st row
 BUILD SUCCESSFUL (total time: 2 seconds)


即使它说有三行,它也只打印了两行。有人可以查看以上是否有问题吗?

最佳答案

很难确定没有看到MenuList类的代码,但是我认为您不需要像ResultSet这样为您遍历MenuList

由于MenuList构造函数将ResultSet中的rs作为参数,因此它可能循环遍历ResultSet以创建其条目。由于您已经在循环的rs.next()中调用了while,因此MenuList会错过第一个结果。

我认为您应该替换所有这些:

MenuList list = null;
while (rs.next()) {
    list = new MenuList(rs);
    System.out.println(rs.getRow());
}


带有:

MenuList list = new MenuList(rs);

10-07 20:46