Java Database Connectivity의 약자 JDBC는 자바에서 데이터베이스에 접속할 수 있게 하는 자바 API로, 데이터베이스에서 자료를 쿼리하거나 업데이트하는 방법을 제공한다.
김영한 강사님의 강의를 보며 학습하였고, H2 데이터베이스를 사용했다.
JDBC 등록
public Member save(Member member) throws SQLException {
String sql = "insert into member(member_id, money) values(?, ?)";
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, member.getMemberId());
pstmt.setInt(2, member.getMoney());
pstmt.executeUpdate();
return member;
} catch (SQLException e) {
log.error("db error", e);
throw e;
} finally {
close(con, pstmt, null);
}
}
Connection con = null; 로 커넥션을 선언하고 PreparedStatement pstmt = null; 로 sql문과 매개변수를 세팅할 객체를 준비했다. try문에서 sql문과 매개변수를 세팅하고 catch문을 통해 예외 발생시 SQLExeption으로 보낼 준비를 하고 finally에서 커넥션을 종료한다.
JDBC 조회
public Member findById(String memberId) throws SQLException {
String sql = "select * from member where member_id = ?";
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, memberId);
rs = pstmt.executeQuery();
if (rs.next()) {
Member member = new Member();
member.setMemberId(rs.getString("member_id"));
member.setMoney(rs.getInt("money"));
return member;
} else {
throw new NoSuchElementException("member not found memberId=" + memberId);
}
} catch (SQLException e) {
log.error("db error", e);
throw e;
} finally {
close(con, pstmt, rs);
}
}
save와 마찬가지로 con, pstmt를 준비하고, ResultSet rs = null; 으로 SELECT 의 결과를 담을 객체를 준비했다. if(rs.next())를 통해 조회를 시작하며 Member 객체를 생성한다. 객체가 존재하지 않을 시 NoSuchElementException이 터짐과 동시에 준비한 문장이 출력 된다. 마찬가지로 close를 통해 커넥션, pstmt 그리고 rs를 종료한다.
JDBC 수정
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);
}
}
JDBC 삭제
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);
}
}
이렇게 connection을 직접 생성하여 세팅하고 종료시키는 것까지 기초적인 것을 배웠다.
김영한 강사님의 강의를 듣고 작성하는 글이기에 강사님의 커리큘럼대로 글이 작성될 것이다.
탄탄한 배경지식과 기술의 출현 이유등을 알려주시려고 예전에 사용하던 코드부터 새롭게 등장한 기술까지 천천히 조립해 나가는 강의를 해주시기에 이 또한 천천히 조립해 나가는 블로그가 될 것이다.
'데이터베이스' 카테고리의 다른 글
트랜잭션 (0) | 2023.03.05 |
---|---|
DataSource와 커넥션 풀 (0) | 2023.03.05 |