首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java JDBC 查詢多條記錄卻只讀到一條:ResultSet.next() 用 if 而非 while

     編輯:程式設計綜合問答

問題代碼

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)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved