최원종의 개발 블로그

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

Java/JAVA 유용한 클래스

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

chl6698 2026. 4. 14. 12:58

실습 코드

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());
        }

    }
}

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

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 로 자동 처리)

 


흐름 이해