首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

JDBC 查詢數據完整流程:ResultSet 遊標操作與資源釋放最佳實踐

     編輯:MySQL 資料庫相關知識

核心類與流程

  • Statement:發送 SQL 命令。
  • ResultSet:封裝查詢結果,內部維護一個指向「第一行之前」的遊標。
  • next():移動遊標到下一行,有資料返回 true,否則 false(等同 Iterator 的 hasNext() + next())。
  • getXxx(列索引/列名):取得當前行指定列的值。

標準查詢範本(含資源安全關閉)

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
    conn = JDBCTools.getConnection();
    stmt = conn.createStatement();
    String sql = "SELECT id, name, email, birth FROM customers WHERE id = 2";
    rs = stmt.executeQuery(sql);
    while (rs.next()) {
        int id = rs.getInt("id");
        String name = rs.getString("name");
        String email = rs.getString("email");
        Date birth = rs.getDate("birth");
        System.out.printf("ID:%d Name:%s Email:%s Birth:%s%n", id, name, email, birth);
    }
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    JDBCTools.release(rs, stmt, conn); // 依序關閉 ResultSet → Statement → Connection
}

關鍵細節

  1. 列索引從 1 開始,非 0;建議使用列名提升可讀性。
  2. getDate() 返回 java.sql.Date,若需 java.util.Date 請轉換。
  3. 必須在 finally 中關閉資源,JDBC 資源不受 GC 管理,洩漏會耗盡連接池。
  4. 生產環境請改用 PreparedStatement 防注入、利用連接池(HikariCP/Druid)複用連接。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved