JDBC(Java Database Connectivity)는 자바에서 데이터베이스에 접속할 수 있도록 하는 자바 API다. JDBC는 데이터베이스에서 자료를 쿼리하거나 업데이트하는 방법을 제공한다.
애플리케이션 서버와 DB는 일반적으로 다음 순서로 사용된다.
1. 애플리케이션 서버에서 DB에 커넥션을 연결한다.
2. 애플리케이션 서버에서 DB에 원하는 SQL 문을 전달한다.
3. DB에서 애플리케이션 서버에 결과를 응답한다.
이 때 MySQL, Oracle(지금은 통합됐지만) 등 각각의 DB마다 사용법이 달랐기 때문에, 다음 두 가지 문제가 생겼다.
이를 해결하기 나온 것이 JDBC 라는 자바 표준이다. 구조는 다음과 같다.
JDBC 는 다음 세 가지 기능을 표준 인터페이스로 정의해서 제공한다.
java.sql.Connection
- 연결java.sql.Statement
- SQL을 담은 내용java.sql.ResultSet
- SQL 요청 응답이 JDBC 인터페이스를 각각의 DB 벤더(회사)에서 자신 의 DB에 맞도록 구현해서 라이브러리로 제공하는데, 이것을 JDBC 드라이버라 한다.
JDBC의 등장으로 다음 2가지 문제가 해결되었다.
1. 데이터베이스를 다른 종류의 데이터베이스로 변경하면 애플리케이션 서버의 데이터베이스 사용 코드도 함께 변경 해야하는 문제
일반적인 부분만 공통화했으므로, DB 변경 시 JDBC 코드는 변경하지 않아도 되지만 SQL은 해당 DB에 맞도록 변경해야 한다. 이는 JPA(Java Persistence API)를 사용 시 상당 부분 해결 가능하다.
JDBC는 1997년에 출시될 정도로 오래된 기술이고, 사용하는 방법도 복잡하다. 그래서 최근에는 JDBC를 직접 사용하기 보다는 JDBC를 편리하게 사용하는 다양한 기술이 존재한다. 대표적으로 SQL Mapper와 ORM 기술로 나눌 수 있다.
SQL Mapper, ORM 과 같은 기술들도 내부에서는 모두 JDBC를 사용한다. 따라서 JDBC를 직접 사용하지는 않더라도, JDBC가 어떻게 동작하는지 기본 원리를 알아두어야 한다. 그래야 해당 기술들을 더 깊이있게 이해할 수 있고, 무엇보다 문제가 발생했을 때 근본적인 문제를 찾아서 해결할 수 있다 JDBC는 자바 개발자라면 꼭 알아두어야 하는 필수 기본 기술 이다.
H2 데이터베이스 서버를 실행한 뒤 실습한다.
package hello.jdbc.connection;
public abstract class ConnectionConst {
public static final String URL = "jdbc:h2:tcp://localhost/~/test";
public static final String USERNAME = "sa";
public static final String PASSWORD = "";
}
package hello.jdbc.connection;
import lombok.extern.slf4j.Slf4j;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import static hello.jdbc.connection.ConnectionConst.*;
@Slf4j
public class DBConnectionUtil {
public static Connection getConnection() {
try {
Connection connection = DriverManager.getConnection(URL, USERNAME,
PASSWORD);
log.info("get connection={}, class={}", connection,
connection.getClass());
return connection;
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
}
DriverManager.getConnection(..)
를 사용하면 된다. 이렇게 하면 라이브러리에 있는 데이터베이스 드라이버를 찾아서 해당 드라이버가 제공하는 커넥션을 반환해준다. 여기서는 H2 데이터베이스 드라이버가 작동해서 실제 데이터베이스와 커넥션을 맺고 그 결과를 반환해준다.DriverManager 커넥션 요청 흐름
1. 애플리케이션 로직에서 커넥션이 필요하면 DriverManager.getConnection()
을 호출한다.
2. DriverManager
는 라이브러리에 등록된 드라이버 목록을 자동으로 인식한다. 이 드라이버들에게 순서대로 다음 정보를 넘겨서 커넥션을 획득할 수 있는지 확인한다.
jdbc:h2:tcp://localhost/~/test
jdbc:h2
로 시작하면 이것은 h2 데이터베이스에 접근하기 위한 규칙이다. 따라서 H2 드라이버는 본인이 처리할 수 있으므로 실제 데이터베이스에 연결해서 커넥션을 획득하고 이 커넥션을 클라이언트에 반환한다. 반면에 URL이 jdbc:h2
로 시작했는데 MySQL 드라이버가 먼저 실행되면 이 경우 본인이 처리할 수 없다는 결과를 반환하게 되고, 다음 드라이버에게 순서가 넘어간다.package hello.jdbc.domain;
import lombok.Data;
@Data
public class Member {
private String memberId;
private int money;
public Member() {
}
public Member(String memberId, int money) {
this.memberId = memberId;
this.money = money;
} }
member
테이블을 미리 만들어두 어야 한다.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(); // connection 획득
pstmt = con.prepareStatement(sql);
pstmt.setString(1, member.getMemberId()); // 위에 sql 의 ? 첫 번째 파라미터 바인딩 해준다.
pstmt.setInt(2, member.getMoney()); // 두 번째 파라미터 바인딩
pstmt.executeUpdate(); // 위에서 준비한 것들(쿼리)이 실제 실행되게 함.(insert 는 Update 문으로)
return member;
} catch (SQLException e) {
log.error("db error", e);
throw e; // 예외 던짐
} finally { // 예외가 발생하던, 하지 않던 항상 수행되어야 하는 부분(close) finally 에 작성.
// 커넥션(외부 리소스)은 실제 TCP,IP 커넥션에 걸려서 쓰는 것으로 안 닫으면 계속 유지됨. 역순으로 닫아줘야 함
// pstmt.close();
// con.close(); // 근데 위에서 예외가 터지면 닫히는 게 호출 자체가 안 될 수도 있어서, close() 메서드를 만들어서 try-catch 로 동작하게 함
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);
}
}
// try 에서 SQLException 이 터지더라도 catch 에서 잡기 때문에 아래 con 에는 영향을 주지 않기 때문에 con 도 닫을 수 있다.
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.info("error", e); // 문제가 생겨도 이미 닫을 때 생기는 거라서, 처리할 수 있는 게 없음. 일단 log 남겨주기.
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
log.info("error", e);
}
}
}
select * from member
쿼리를 실행하면 데이터가 저장된 것을 확인할 수 있다.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(); // select 는 Query 문으로. 이건 결과를 ResultSet(rs)에 담아서 반환해준다.
if (rs.next()) { // rs(ResultSet)는 내부에 커서같은 게 있어서, 한 번 호출을 해줘야 실제 데이터가 있는 곳부터 실행이 됨. next() 는 첫 번째 데이터가 있는지를 물어봐서 true 면 진행
Member member = new Member(); // 멤버 객체 만들어서 저장해주기
member.setMemberId(rs.getString("member_id"));
member.setMoney(rs.getInt("money"));
return member;
} else { // false 나와서~
throw new NoSuchElementException("member not found memberId=" + memberId); // 예외를 던질 땐 메시지를 잘 넣는 게 좋다. 문제 터졌을 때 해결하기 좋음
}
} catch (SQLException e) {
log.info("db error", e);
throw e;
} finally {
close(con, pstmt, rs);
}
}
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);
}
}
...
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);
} }