Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

JDBC 개발 - 수정, 삭제 본문

인프런/[인프런] 스프링 DB 1편 - 데이터 접근 핵심 원리

JDBC 개발 - 수정, 삭제

Seung__ 2022. 5. 28. 23:19

수정과 삭제는 앞서 살펴본 등록과 비슷하다.

 

데이터를 변경하는 쿼리를 executeUpdate()를 통해 실행하면 된다.

 

두 메서드는 쿼리만 다르고 전체 흐름을 동일하다.

public void update(String memberId, int money) throws SQLException {
    String sql = "update member set money=? where member_id=?";

    Connection con = null;
    PreparedStatement pstmt = null;

    try {
        con = getConnection();
        pstmt = con.prepareStatement(sql);
        pstmt.setInt(1, money); //첫 번째 파라미터 바인딩
        pstmt.setString(2, memberId); //두 번째 파라미터 바인딩
        int resultSize = pstmt.executeUpdate();
        log.info("resultSize={}", resultSize);
    } catch (SQLException e) {
        log.info("db error", e);
        throw e;
    }finally {
        close(con, pstmt, null);
    }
}

public void delete(String memberId) throws SQLException {
    String sql = "delete from member where member_id=?";
    Connection con = null;
    PreparedStatement pstmt = null;

    try {
        con = getConnection();
        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, memberId);
        int resultSize = pstmt.executeUpdate();
        log.info("resultSize={}", resultSize);
    } catch (SQLException e) {
        log.info("db error", e);
        throw e;
    }finally {
        close(con, pstmt, null);
    }
}

 

Test

//update: money 10000 -> 20000
repository.update(member.getMemberId(), 20000);
Member updatedMember = repository.findById(member.getMemberId());
assertThat(updatedMember.getMoney()).isEqualTo(20000);

//delete
repository.delete(member.getMemberId());
assertThatThrownBy(() -> repository.findById(member.getMemberId()))
        .isInstanceOf(NoSuchElementException.class);

exception이 터지는 경우를 어떻게 테스트 할까?

assertThatThrownBy()를 이용하면 된다.

assertThatThrownBy(() -> "exception 발생하는 로직").isInstanfceOf(발생하는 Exception)

 

 

'인프런 > [인프런] 스프링 DB 1편 - 데이터 접근 핵심 원리' 카테고리의 다른 글

Data Source 이해  (0) 2022.05.29
커넥션 풀 이해  (0) 2022.05.29
JDBC 개발-조회  (0) 2022.05.23
JDBC개발-등록  (0) 2022.05.23
DB 연결  (0) 2022.05.22
Comments