JDBC 구성 요소(아키텍처) - 2

Kim taegwan·2026년 4월 5일
package ch02;

import java.sql.*;

public class Step1Statement {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/shop?serverTimezone=Asia/Seoul";
        String user = System.getenv("DB_USER"); // 환경 변수에 저장 되어 있음
        String password = System.getenv("DB_PASSWORD"); // 환경 변수에 저장 되어 있음

        try (Connection connection = DriverManager.getConnection(url, user, password)) {
            // 1. Connection 객체 필요 - 생성 - 세션 생성(논리적으로 연결된 상태를 의미함 )
            // 2. Statement 객체 필요 ( 문자열을 쿼리 객체로 변경 해 줌)
            // 3. ResultSet 객체 필요 (쿼리가 실행 되면 결과집합을 담고 있는 녀석)
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM product");
            System.out.println("==== 상품 목록 출력 ====");
            // rs.next() --> 다음 행이 존재 하는가? --> true , false
            while (rs.next()) {
               int id =  rs.getInt("id");
               int categoryId = rs.getInt("category_id");
               String name = rs.getString("name");
                System.out.println("상품 ID : " + id
                                   + " | 카테고리ID " + categoryId + " | 상품명 " + name );
            }
        } catch (SQLException e) {
            System.out.println("오류 발생 : " + e.getMessage());
            System.out.println("SQLState : " + e.getSQLState());
        }

    } // end of main

} // end of class
package ch02;

import java.sql.*;

public class Step2PreparedStatement {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/shop?serverTimezone=Asia/Seoul";
        String user = System.getenv("DB_USER");
        String pwd = System.getenv("DB_PASSWORD");

        int maxPrice = 50000; // 5만원 이하 상품 검색 예정
        try (Connection conn = DriverManager.getConnection(url, user, pwd)) {
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM product where price <=  ? ");
            pstmt.setInt(1, maxPrice);
            // 쿼리 실행
            // SELECT - executeQuery()
            // INSERT, UPDATE, DELETE - executeUpdate()
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    System.out.printf("%-20s %,d원 (재고: %d개)%n",
                            rs.getString("name"),
                            rs.getInt("price"),
                            rs.getInt("stock"));
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    } // end of main
} // end of class

2번째문은 ststement가 아니라 PreparedStatement을 썼는데 좀더 간편하게 쓸수 있고 보안상 더 안전하다.

1단원 복습 - 우리가 작성한 코드 다시 보기

1단원에서 이 코드를 작성했습니다.

try (Connection connection = DriverManager.getConnection(url, user, password)) {
    System.out.println("연결 성공!");
}

짧은 코드지만 내부에서는 여러 구성 요소가 함께 동작하고 있습니다.
이번 단원에서는 그 구성 요소 하나하나가 무슨 역할을 하는지 파악합니다.


JDBC 아키텍처 전체 흐름

자바 애플리케이션
       │
       ▼
  DriverManager  ← 드라이버 관리자 (적절한 드라이버를 찾아줌)
       │
       ▼
    Driver       ← 각 DB 제조사가 구현 (MySQL 드라이버, Oracle 드라이버 등)
       │
       ▼
  Connection     ← DB 와의 연결 통로 (세션)
       │
       ▼
  Statement      ← SQL 을 DB 에 전달하는 도구
  PreparedStatement
       │
       ▼
  ResultSet      ← SQL 실행 결과를 담는 그릇

Connection 의 주요 메서드:

connection.createStatement()      // Statement 생성
connection.prepareStatement(sql)  // PreparedStatement 생성
connection.setAutoCommit(false)   // 수동 트랜잭션 모드
connection.commit()               // 트랜잭션 커밋
connection.rollback()             // 트랜잭션 롤백
connection.close()                // 연결 종료 (try-with-resources 로 자동 처리)

이렇게 rs.next를 통해서 다음행 다음행을 불러온다.

0개의 댓글