ResultSet 封裝了 JDBC 查詢操作的完整結果集,是資料庫交互中的核心數據容器。掌握其工作機制對高效開發至關重要。
Statement.executeQuery(sql) 方法獲得next() 方法同時完成「判斷是否有下一行」與「游標下移」兩個動作,類似 Iterator 的 hasNext() + next() 組合getXxx(index) 或 getXxx(columnName) 獲取列值,如 getInt(1)、getString("name")@Test
public void testResultSet() {
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
try {
// 1. 獲取連接
connection = JDBCTools.getConnection();
// 2. 創建 Statement
statement = connection.createStatement();
// 3. 準備 SQL
String sql = "SELECT * FROM CUSTOMERS WHERE ID = 2";
// 4. 執行查詢
rs = statement.executeQuery(sql);
// 5. 處理結果集
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.println(id + "\t" + name + "\t" + email + "\t" + birth);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 6. 釋放資源(順序:ResultSet → Statement → Connection)
JDBCTools.release(rs, statement, connection);
}
}
JDBCTools.release() 已封裝重載方法支援多參數getString("columnName") 提高代碼可讀性與維護性,避免 SELECT * 導致列序變更報錯此為 JDBC 查詢最基礎範式。實際項目中建議採用連接池、PreparedStatement 防注入、ORM 框架等進階方案提升健壯性與開發效率。