데이터를 삽입하거나 수정하는 것과 달리, SELECT 쿼리는 조회한 데이터를 반환받아 처리해야 합니다. 이때 ResultSet 객체를 사용하여 쿼리 결과를 관리합니다.
ResultSet은 SQL의 SELECT 쿼리 결과를 담고 있는 객체입니다.Statement.executeQuery()나 PreparedStatement.executeQuery() 메서드가 반환하는 객체입니다. while (rs.next())와 같은 반복문을 통해 행을 순차적으로 접근하며 데이터를 처리합니다.next() - 다음 행으로 이동하며, 데이터가 있으면 true를 반환하고 없으면 false를 반환합니다.getInt(), getString() 등 - 특정 열의 데이터를 가져올 때 사용됩니다.package com.exam;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ResultSetEx01 {
public static void main(String[] args) {
System.out.println("시작");
String url = "jdbc:mariadb://localhost:3306/sample";
String user = "root";
String password = "123456";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// MariaDB JDBC 드라이버 로드
Class.forName("org.mariadb.jdbc.Driver");
System.out.println("드라이버 로딩 성공");
// 데이터베이스에 연결
conn = DriverManager.getConnection(url, user, password);
System.out.println("데이터베이스 연결 성공");
// Statement 객체 생성
stmt = conn.createStatement();
// SQL 쿼리 작성 - 데이터 조회
String sql = "SELECT * FROM dept2";
rs = stmt.executeQuery(sql); // 쿼리 실행 및 결과 저장
// ResultSet을 사용해 결과 출력
while (rs.next()) {
int deptno = rs.getInt("deptno"); // "deptno" 열의 값 가져오기
String dname = rs.getString("dname"); // "dname" 열의 값 가져오기
String loc = rs.getString("loc"); // "loc" 열의 값 가져오기
System.out.printf("부서번호: %d, 부서명: %s, 위치: %s%n", deptno, dname, loc);
}
} catch (ClassNotFoundException e) {
System.out.println("[에러] 드라이버 로딩 실패: " + e.getMessage());
} catch (SQLException e) {
System.out.println("[에러] SQL 실행 오류: " + e.getMessage());
} finally {
// ResultSet, Statement, Connection 객체 닫기
if (rs != null) { try { rs.close(); } catch (SQLException e) { } }
if (stmt != null) { try { stmt.close(); } catch (SQLException e) { } }
if (conn != null) { try { conn.close(); } catch (SQLException e) { } }
}
System.out.println("끝");
}
}