JDBC

HUSII·2023년 2월 11일
0

스프링 DB

목록 보기
1/4

JDBC의 등장 이유

데이터베이스에 데이터를 저장할때는 3개의 과정이 있다.
1. 커넥션 연결
2. SQL 전달
3. 결과 응답
이때 MySQL 드라이버를 쓸수도 있고, Oracle 드라이버를 쓸수도 있다.
각각의 드라이버를 사용할때의 문법이 다르다.
이를 추상화시킨 인터페이스가 JDBC이다.

JDBC를 사용하면 드라이버를 변경해도 코드를 고칠 필요가 없어진다.

일부 SQL은 변경해줘야한다. 대부분의 코드는 고칠 필요 없음

JDBC 사용 코드 예시

public Member save(Member member) throws SQLException {
	// 새로운 멤버를 데이터베이스에 추가하는 SQL
	String sql = "insert into member(member_id, money) values(?, ?)";
	Connection con = null;
	PreparedStatement pstmt = null;
	try {
		con = getConnection(); // 1. 커넥션 연결
        
		pstmt = con.prepareStatement(sql);
		pstmt.setString(1, member.getMemberId());
		pstmt.setInt(2, member.getMoney());
        
		pstmt.executeUpdate(); // 2. SQL 전달, 3. 결과 응답
		return member;
	} catch (SQLException e) {
		log.error("db error", e);
		throw e;
	} finally {
		close(con, pstmt, null);
	}
}

private void close(Connection con, Statement stmt, ResultSet rs) {
	if (rs != null) {
		try {
			rs.close();
		} catch (SQLException e) {
			log.info("error", e);
		}
	}
	if (stmt != null) {
		try {
			stmt.close();
		} catch (SQLException e) {
			log.info("error", e);
		}
	}
	if (con != null) {
		try {
			con.close();
		} catch (SQLException e) {
			log.info("error", e);
		}
	}
}
private Connection getConnection() {
	return DBConnectionUtil.getConnection();
}
profile
공부하다가 생긴 궁금한 것들을 정리하는 공간

0개의 댓글