본문 바로가기

(09.15) JDBC 프로그래밍 - JDBC, Gradle/Maven, executeUpdate/executeQuery, DAO/DTO

@starweb2025. 9. 15. 19:30

[ 6주차 - 0915 ] 

    금일 커리큘럼
        ├ 09:00 ~ 12:00 JDBC 프로그래밍 (JDBC, Gradle/Maven, JDBC 절차)
        └ 13:00 ~ 18:00 JDBC 프로그래밍 (executeUpdate/executeQuery, DAO/DTO 패턴)

1. JDBC

JDBC ? 자바에서 데이터베이스에 접속하고 SQL을 실행할 수 있게 해주는 표준 API

  • 자바는 DB와 직접 대화할 수 없음 → DB마다 접속 방식, 프로토콜이 다르기 때문
  • 그래서 DBMS별로 제공되는 JDBC 드라이버가 필요함
  • DB 벤더(MySQL/Oracle 등)가 달라도 자바 코드는 JDBC 표준을 사용하므로 코드 변경을 최소화

2. JDBC 관련 Gradle/Maven 의존성

Gradle/Maven: 빌드·의존성 관리·테스트·실행을 자동화하는 빌드 도구

  • JDBC 프로그래밍 시작 전에 JDBC 드라이버를 클래스패스에 추가해야 하는데 일반적으로 Gradle or Maven 의존성 빌드 사용함

 

인텔리제이 Gradle 설정

그래들 (프로젝트 신규 생성시)

  • 1. [파일] -> [새로만들기] -> [프로젝트] 클릭
  • 2. 시스템빌드 gradle 선택 / DSL groovy 선택 후 확인
  • 3. 프로젝트 루트에서 bulid.gradle 파일 내용 dependencies 수정
dependencies {
    implementation("com.mysql:mysql-connector-j:8.3.0")
    testImplementation platform('org.junit:junit-bom:5.10.0')
    testImplementation 'org.junit.jupiter:junit-jupiter'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

그래들 (기존 프로젝트 유지시)

  • 1. 프로젝트 최상위 루트에서 build.gradle, settings.gradle 두개 파일 생성
  • 2. build.gradle , settings.gradle 파일 내용 다음과 같이 입력

build.gradle

plugins {
    id 'java'
}

group = 'org.example'
version = '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

sourceSets {
    main {
        java {
            srcDirs = ['src']
        }
    }
}

dependencies {
    implementation("com.mysql:mysql-connector-j:8.3.0")
    testImplementation platform('org.junit:junit-bom:5.10.0')
    testImplementation 'org.junit.jupiter:junit-jupiter'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

test {
    useJUnitPlatform()
}

settings.gradle

rootProject.name = '프로젝트명'
  • 3. 프로젝트 다시 로드 후 우측 [gradle 아이콘] -> [새로고침(동기화)] 버튼 클릭
  • 4. 소스루트 오류시 [파일] -> [프로젝트구조] 에서 [모듈] 선택 후 최상위루트 [오른쪽마우스] 클릭해서 [소스] 선택

gradle 빌드 후 java에서 sout해도 안나오는 경우

  • [파일] -> [설정] -> [빌드,실행,배포] -> [빌드도구] -> [gradle] 에서 빌드 및 실행, 테스트 실행 전부 인텔리제이로 변경

 

인텔리제이 Maven 설정

  • 메이븐 (pom.xml을 이용한 정형화된 빌드 시스템)
    • 1. [파일] -> [프로젝트구조] 클릭
    • 2. 사이드 [라이브러리] 선택 후 [+] 버튼클릭하여 maven 선택
    • 3. mysql:mysql-connector-java:8.0.33 검색 후 적용

3. JDBC 프로그래밍 과정

JDBC 프로그래밍 절차

DriverManager  # 드라이버 관리, DB 연결 요청
      │
      ↓
    Driver      # 실제 DB 벤더 드라이버
      │
      ↓
  Connection    # DB 연결
      │
  ┌───┴───────────┐
  ↓               ↓
Statement   PreparedStatement   # SQL 실행
# 문자열       # 바인딩 방식
   └─────┬───────┘
         ↓
    ResultSet   # SELECT 결과 집합(테이블 형태 데이터)

사용 예시

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class UpdateTest {
    public static void main(String[] args) {
        // DB 정보
        String url = "jdbc:mysql://localhost:3306/liondb";
        String user = "root";
        String password = "root1234";

        // SQL 쿼리문
        String sql = "update dept set dname=? where deptno=?";
        try (
            // getConnection으로 해당 DB 접근 객체 생성
            Connection conn = DriverManager.getConnection(url,user,password);
            // 미리 작성된 SQL 문을 준비 → ?(파라미터 바인딩) 가능
            PreparedStatement ps = conn.prepareStatement(sql)
        ) {
            ps.setString(1,"변경"); // dname=? 첫번째 자리 바인딩
            ps.setInt(2,50);       // deptno=? 두번째 자리 바인딩

            // 준비된 SQL 실행 (executeUpdate = insert, update, delete 조작어)
            int resultCnt = ps.executeUpdate();

            // 실행 성공 여부 (행변경 수)
            if(resultCnt > 0) System.out.println("성공");
            else System.out.println("실패");

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}
  • Connection = 자바에서 DB와의 연결(세션)을 표현하는 객체
  • PreparedStatement() = '?' 인자를 통해 바인딩 접근 방식
  • executeUpdate() = insert, update, delete, create, drop 실행 결과 반환 (int)
  • executeQuery() = select 전용 ResultSet 객체 반환
  • ResultSet = 자바에서 db의 테이블 형태 정보를 다루는 객체임
    • rs.next()로 행 단위 탐색
    • rs.getString("컬럼명") 으로 해당 컬럼의 데이터 얻음

4. execute 사용

executeUpdate() - insert, update, delete

insert 예시

public class InsertTest {
    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://localhost:3306/liondb";
        String user = "root";
        String password = "root1234";

        String sql = "insert into dept(deptno, dname, loc) values (?,?,?)";
        try (
            Connection conn = DriverManager.getConnection(url,user,password);
            PreparedStatement ps = conn.prepareStatement(sql)
        ) {
            ps.setInt(1,50);
            ps.setString(2,"lion");
            ps.setString(3,"seoul");

            int resultCnt = ps.executeUpdate();
            if(resultCnt == 1) System.out.println("성공");
            else System.out.println("실패");

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

delete 예시

public class DeleteTest {
    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://localhost:3306/liondb";
        String user = "root";
        String password = "root1234";

        String sql = "delete from dept where deptno = ?";
        try (
            Connection conn = DriverManager.getConnection(url,user,password);
            PreparedStatement ps = conn.prepareStatement(sql)
        ) {
            ps.setInt(1, 50);

            int resultCnt = ps.executeUpdate();
            if(resultCnt == 1) System.out.println("성공");
            else System.out.println("실패");

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

update 예시

public class UpdateTest {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/liondb";
        String user = "root";
        String password = "root1234";

        String sql = "update dept set dname=? where deptno=?";
        try (
                Connection conn = DriverManager.getConnection(url,user,password);
                PreparedStatement ps = conn.prepareStatement(sql)
        ) {
            ps.setString(1,"변경");
            ps.setInt(2,50);

            int resultCnt = ps.executeUpdate();
            if(resultCnt == 1) System.out.println("성공");
            else System.out.println("실패");

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

executeQuery - select

select 예시

public class SelectTest {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/liondb";
        String user = "root";
        String password = "root1234";

        String sql = "select deptno, dname, loc from dept where deptno = ?";
        try (
            Connection conn = DriverManager.getConnection(url,user,password);
            PreparedStatement ps = conn.prepareStatement(sql)
        ) {
            ps.setInt(1, 10);
            try (ResultSet rs = ps.executeQuery()) {
                // 6) 결과 읽기: 행이 있으면 커서가 다음 행으로 이동하고 true
                if (rs.next()) {
                    // 컬럼 라벨(이름)으로 꺼내는 게 안전
                    int deptno      = rs.getInt("deptno");
                    String dname    = rs.getString("dname");
                    String loc      = rs.getString("loc");

                    System.out.printf("성공: deptno=%d, dname=%s, loc=%s%n", deptno, dname, loc);
                } else {
                    System.out.println("실패(해당 조건의 행이 없음)");
                }
            }

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

5. DAO / DTO 패턴

DB 테이블 정보 접근 및 정보 관리하는 개발 패턴

DTO (Data Transfer Object)

  • 역할 : DB의 테이블 한 행(row) 구조를 담는 객체
  • 단순히 데이터를 담고 전달하기 위한 그릇임
  • getter/setter 메서드랑 toString 정도만 포함함
public class DeptDTO {
    private int deptno;
    private String dname;
    private String loc;

    public int getDeptno() {
        return deptno;
    }

    public void setDeptno(int deptno) {
        this.deptno = deptno;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }


    @Override
    public String toString() {
        return "DeptDTO{" +
                "deptno=" + deptno +
                ", dname='" + dname + '\'' +
                ", loc='" + loc + '\'' +
                '}';
    }
}

DAO (Data Access Object)

  • 역할 : DB에 직접 접근해서 CRUD 실행하는 객체
  • SQL 실행(select, insert, update, delete)을 전담
  • 내부에서 Connection, PreparedStatement, ResultSet 사용
    • Connection 정도는 따로 유틸 클래스로 만들기도 함

getConnection 용 유틸 class

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
    static final String url = "jdbc:mysql://localhost:3306/liondb";

    public static Connection getConnection() throws Exception {
        String user = "root";
        String password = "root1234";

        return DriverManager.getConnection(url, user, password);
    }

    // Connection 클로즈 제공
    public static void close(Connection conn) {
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
    // ResultSet 클로즈 제공
    public static void close(ResultSet rs) {
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

sql 실행 전담 DAO class

import week_06._0915.lionDB.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class DeptDAO {

    /** 튜플 삭제 */
    public static boolean deleteDept(DeptDTO deptDTO){
        String sql = "delete from dept where deptno=?";
        int resultCount = 0;

        try(
            Connection conn = DBUtil.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql)
        ) {
            ps.setInt(1, deptDTO.getDeptno());
            resultCount = ps.executeUpdate();
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }

        return resultCount > 0;
    }

    /** 튜플 변경 */
    public static boolean updateDept(DeptDTO deptDTO){
        String sql = "update dept set dname=? where deptno=?";
        int resultCount = 0;

        try(
            Connection conn = DBUtil.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql)
        ) {
            ps.setString(1, deptDTO.getDname());
            ps.setInt(2, deptDTO.getDeptno());
            resultCount = ps.executeUpdate();
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }

        return resultCount > 0;
    }

    /** 튜플 추가 */
    public static boolean insertDept(DeptDTO deptDTO){
        String sql = "insert into dept(deptno, dname, loc) values (?,?,?)";
        int resultCount = 0;

        try(
            Connection conn = DBUtil.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql)
        ) {
            ps.setInt(1, deptDTO.getDeptno());
            ps.setString(2, deptDTO.getDname());
            ps.setString(3, deptDTO.getLoc());
            resultCount = ps.executeUpdate();
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }

        return resultCount > 0;
    }

    /** 단건 조회 */
    public static DeptDTO getDept(int deptno) {
        String sql = "select deptno, dname, loc from dept where deptno = ?";
        DeptDTO deptDTO = null;
        ResultSet rs = null;

        try(
            Connection conn = DBUtil.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql)
        ) {
            // 스테이트먼트 셋 먼저 적용후 익스큐트쿼리 써야함.
            ps.setInt(1, deptno);
            rs = ps.executeQuery();
            if(rs.next()) {
                deptDTO = new DeptDTO();
                deptDTO.setDeptno(rs.getInt("deptno"));
                deptDTO.setDname(rs.getString("dname"));
                deptDTO.setLoc(rs.getString("loc"));
            }
        } catch(Exception e) {
            System.out.println(e.getMessage());
        } finally {
            DBUtil.close(rs);
        }

        return  deptDTO;
    }

    /** 전체 조회 */
    public static List<DeptDTO> getAll() {
        String sql = "select deptno, dname, loc from dept";
        List<DeptDTO> list = new ArrayList<>();

        try(
            Connection conn = DBUtil.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery()
        ) {

            while (rs.next()) {
                DeptDTO deptDTO = new DeptDTO();
                deptDTO.setDeptno(rs.getInt(1));
                deptDTO.setDname(rs.getString(2));
                deptDTO.setLoc(rs.getString(3));
                list.add(deptDTO);
            }

        } catch(Exception e) {
            System.out.println(e.getMessage());
        }

        return list;
    }
}
starweb
@starweb :: starweb 님의 블로그

starweb 님의 블로그 입니다.

공감하셨다면 구독도 환영합니다!

목차