if (rs.next()) { // 錯誤:只判斷一次
Gameperson gp = new Gameperson();
gp.setId(rs.getInt("id"));
// ...
list.add(gp);
}
ResultSet.next() 將游標移動到下一行並返回 boolean。用 if 只處理第一行,必須用 while 循環遍歷所有行。
while (rs.next()) { // 正確:循環直到無下一行
Gameperson gp = new Gameperson();
gp.setId(rs.getInt("id"));
gp.setCompetitorId(rs.getInt("competitorId"));
gp.setGameId(rs.getInt("gameId"));
list.add(gp);
}
public List<Gameperson> getGamePerson() {
List<Gameperson> list = new ArrayList<>();
String sql = "SELECT * FROM gameperson";
try (Connection conn = DBO.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
Gameperson gp = new Gameperson();
gp.setId(rs.getInt("id"));
gp.setCompetitorId(rs.getInt("competitorId"));
gp.setGameId(rs.getInt("gameId"));
list.add(gp);
}
} catch (SQLException e) {
e.printStackTrace(); // 生產環境請用日誌框架
}
return list;
}
try-with-resources(JDK 7+)自動關閉資源,防止洩漏。SELECT *,顯式列出欄位名,提升性能與穩定性。LIMIT offset, size)或流式讀取(setFetchSize)。