contents

JDBC(Java Database Connectivity)에 대해 설명드리겠습니다.


1. JDBC란 무엇인가?


2. JDBC 아키텍처

2티어 구조

3티어 구조


3. JDBC의 주요 구성 요소

클래스/인터페이스 설명
DriverManager JDBC 드라이버 로딩, 커넥션 생성, 드라이버 관리 역할
Connection 데이터베이스와의 세션/연결을 표현
Statement SQL 쿼리 실행용; 정적인 단순 쿼리
PreparedStatement 파라미터를 가진 동적 쿼리, 사전 컴파일되어 성능, 보안 우수
CallableStatement DB의 저장 프로시저 호출에 사용
ResultSet 쿼리 실행 결과 집합을 행/열 단위로 탐색
SQLException SQL 실행 중 오류 발생 시 예외 처리

4. JDBC 드라이버의 종류


5. JDBC 기본 동작 흐름(순서)

  1. 드라이버 로딩
    Class.forName("com.mysql.cj.jdbc.Driver");
  2. 커넥션(Connection) 생성
    Connection conn = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/your_db", 
        "username", "password");
  3. Statement/PreparedStatement 생성
    Statement stmt = conn.createStatement();
    // OR
    PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM table WHERE id = ?");
    pstmt.setInt(1, 10);
  4. SQL 쿼리 실행 및 결과 처리
    ResultSet rs = stmt.executeQuery("SELECT * FROM table");
    while (rs.next()) {
        String name = rs.getString("name");
    }
  5. 자원 해제 (커넥션/스테이트먼트/결과셋 닫기)
    rs.close();
    stmt.close();
    conn.close();

6. 주요 특징 및 실무 활용


7. 실제 사용 예시

import java.sql.*;
public class JDBCExample {
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "pass");
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT id, name FROM user");
        while (rs.next()) {
            System.out.println(rs.getInt("id") + " " + rs.getString("name"));
        }
        rs.close();
        stmt.close();
        conn.close();
    }
}

8. 실무시 주의사항 & 베스트프랙티스


9. JDBC 활용 방식 비교 요약

JDBC 단독 Spring JDBC/JPA
저수준 직접 연결, 쿼리, 예외 처리 모두 수동 API 추상화로 간편, 에러 및 자원관리 자동화
적합도 학습, 단순/제어가 필요한 작업 실무 프로덕션 코드/복잡한 비즈니스 로직

JDBC는 자바에서 데이터베이스와 직접 연동할 때 반드시 마스터해야 할 기본 API입니다. Spring Framework(특히 JdbcTemplate, JPA 등)는 이를 효율적으로 감싸주는 추상화를 제공하므로 JDBC의 기초 구조와 사용법을 정확히 이해하면 더욱 견고한 데이터 연동 코드를 작성할 수 있습니다.

references