gpt4 book ai didi

java - 结果集返回 3 行,但我只能打印 2 行?

转载 作者:行者123 更新时间:2023-12-02 07:56:47 25 4
gpt4 key购买 nike

下面的代码从数据库中获取我需要的信息,但没有打印出所有信息。首先,我知道它从表中获取了所有正确的信息,因为我已经在 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 进行循环code> 会为你做到这一点。

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

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

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

与:

MenuList list = new MenuList(rs);

关于java - 结果集返回 3 行,但我只能打印 2 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9517197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com