JDBC에서 ResultSet 인터페이스는 SQL 쿼리 실행 결과로 생성된 테이블 형태의 데이터를 표현합니다. ResultSet은 현재 행(row)을 가리키는 커서(cursor)를 가지고 있으며, 처음에는 이 커서가 첫 번째 행 바로 앞에 위치합니다.
next() 메서드를 호출하면 커서를 다음 행으로 이동시킬 수 있고, ResultSet 인터페이스가 제공하는 getter 메서드(getInt(), getString(), getDate() 등)를 사용해 해당 행의 컬럼 값을 가져올 수 있습니다.
테이블에서 원하는 데이터 조회하기
테이블에서 필요한 데이터를 조회하려면 다음 단계를 따릅니다.
- 데이터베이스에 연결합니다.
- Statement 객체를 생성합니다.
- executeQuery() 메서드를 사용해 쿼리를 실행합니다. 이 메서드에는 String 형식의 SELECT 쿼리를 전달합니다.
모든 값을 조회하려면 아래와 같이 *(와일드카드)를 사용합니다.
SELECT * FROM TableName;
반면, 특정 열만 조회하고 싶다면 * 대신 필요한 컬럼 이름을 명시적으로 지정하면 됩니다.
SELECT Name, DOB FROM Emp
예제
데이터베이스에 다음과 같은 구조의 Emp 테이블이 있다고 가정해 보겠습니다.
+----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | DOB | date | YES | | NULL | | | Location | varchar(255) | YES | | NULL | | +----------+--------------+------+-----+---------+-------+
아래 JDBC 예제는 Emp 테이블에서 직원들의 Name(이름)과 DOB(생년월일) 값만 조회합니다.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingParticularColumn {
public static void main(String args[]) throws Exception {
// 드라이버 등록
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
// 데이터베이스 연결
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
// Statement 객체 생성
Statement stmt = con.createStatement();
// 데이터 조회 — Name과 DOB 컬럼만 선택
ResultSet rs = stmt.executeQuery("select Name, DOB from Emp");
System.out.println("Contents of the table");
while(rs.next()) {
System.out.print("Name of the Employee: "+rs.getString("Name")+", ");
System.out.print("Date of Birth: "+rs.getDate("DOB"));
System.out.println("");
}
}
}실행 결과
위 코드를 실행하면 다음과 같이 Name과 DOB 두 컬럼의 값만 출력되는 것을 확인할 수 있습니다.
Connection established...... Contents of the table Name of the Employee: Amit, Date of Birth: 1970-01-08 Name of the Employee: Sumith, Date of Birth: 1970-01-08 Name of the Employee: Sudha, Date of Birth: 1970-01-05
이처럼 SELECT 문에서 필요한 컬럼명만 지정하면 전체 데이터가 아닌 원하는 열만 효율적으로 조회할 수 있으며, 불필요한 데이터 전송을 줄여 애플리케이션 성능 향상에도 도움이 됩니다.