[DB 접근 기술] JDBC 개발 - 수정, 삭제

2022. 5. 25. 05:48Database/DB 접근 기술

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-db-1#

 

스프링 DB 1편 - 데이터 접근 핵심 원리 - 인프런 | 강의

백엔드 개발에 필요한 DB 데이터 접근 기술을 기초부터 이해하고, 완성할 수 있습니다. 스프링 DB 접근 기술의 원리와 구조를 이해하고, 더 깊이있는 백엔드 개발자로 성장할 수 있습니다., - 강의

www.inflearn.com

김영한 강사님의 인프런 강의를 수강 후 블로그에 정리해서 포스팅합니다. 


이전 포스팅의 등록, 조회에 이어 수정, 삭제를 알아본다.
먼저 수정

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.error("db error", e);
         throw e;
     } finally {
     	close(con, pstmt, null);
     }
}

executeUpdate() 는 쿼리를 실행하고 영향받은 row수를 반환한다.
여기서는 하나의 데이터만 변경하기 때문에 결과로 1이 반환된다.

삭제 코드도 거의 비슷하다.

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);
         pstmt.executeUpdate();
     } catch (SQLException e) {
         log.error("db error", e);
         throw e;
     } finally {
     	close(con, pstmt, null);
     }
}