核心類與流程
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 開始,非 0;建議使用列名提升可讀性。
getDate() 返回 java.sql.Date,若需 java.util.Date 請轉換。
- 必須在 finally 中關閉資源,JDBC 資源不受 GC 管理,洩漏會耗盡連接池。
- 生產環境請改用
PreparedStatement 防注入、利用連接池(HikariCP/Druid)複用連接。