Search
Duplicate
📒

[Database Study] 04-2. JDBC 드라이버 등록, 간단한 CRUD

상태
미진행
수업
Database Study
주제
JDBC
4 more properties
참고

데이터베이스 JDBC 커넥션

NOTE
JDBC 커넥션을 얻어서, h2 데이터베이스에 연결하자!

ConnectionConst 구현 (DB 연결에 필요한 정보)

NOTE
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 = ""; }
Java
복사
ConnectionConst 코드
h2에 연결하기 위한 상수 정보만을 담은 클래스를 만들어준다
아래의 변수들을 이용해 정보를 호출한다

JDBC DriverManager 연결 이해

NOTE
JDBCjava.sql.Connecion 표준 커넥션 인터페이스를 정의한다
H2 데이터베이스 드라이버JDBC Connection 인터페이스를 구현한 org.h2.jdbc.JdbcConnection 구현체를 제공한다
DriverManager 커넥션 요청 흐름
@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); } } }
Java
복사
JAVA에서 데이터베이스에 연결하려면 JDBC가 제공하는 DriverManager.getConnection() 메소드를 사용해서 얻어와야 한다.
JDBC DriverManager ⇒ JDBC 드라이버 세트를 관리하기 위한 기본 서비스이다.
DriverManager 초기화 ⇒ 느리게 수행되며 스레드 컨텍스트 클래스 로더를 사용하여 서비스 공급자를 찾는다
getConnection 과정
1.
애플리케이션 로직에서 Connection이 필요하면 DriveManger.getConnectino() 호출
2.
DriverManager는 라이브러리에 등록된 드라이버 목록을 자동으로 인식한다.
a.
순서대로 다음 정보를 넘겨서 커넥션을 획득할 수 있는지 확인
b.
URL → "jdbc:h2:tcp://localhost/~/test"
c.
이름, 비밀번호 등 접속에 필요한 정보
d.
각각의 드라이버가 URL 정보를 체크한후 본인이 처리가능한지 확인함 ex) jdbc:h2로 시작하면 h2 데이터베이스에 접근한다
e.
따라서 H2드라이버에서 연걸해서 커넥션을 획득하고 클라이언트에게 준다 반면 MySQL 드라이버같은 경우는 본인이 처리 못하므로 처리못하는 결과를 반환해주고 다음 드라이버에게 넘긴다
3.
이런식으로 찾은 Connection 구현체가 클라이언트에게 반환

JDBC 를 사용한 간단한 CRUD

NOTE
JDBC를 사용하여 DriveManager로 직접 Connection을 얻어와 디비에 연결해 쿼리를 날려보는 로직을 짠다
JDBC 흐름도
@Data public class Member { private String memberId; private int money; }
Java
복사
데이터 클래스

MemberRepository (CRUD)

NOTE
Connection을 얻어 쿼리를 날리는 Repository를 작성한다
1.
Connection을 얻는다
2.
Connection을 받을 객체를 null로 초기화하는 이유는, SQL ExceptionChecked Exception이기 때문에 try, catch로 처리해주기 위함
3.
PreparedStatement 객체를 이용해 쿼리를 DB에 보낸다
4.
모든 처리가 끝났으면, 연결된 Connection을 순차적으로 끊는다 ( con, pstmt, rs )
5.
ResultSet은 DB에서 불러온 결과를 저장해 cursor을 이용해 값을 조회하는 역할을 한다.
PreparedStatement
Statement 사용 시의 문제점 (SQL Injection)
SQL을 그대로 전달하게하는 문제점이 발생
PreparedStatement를 사용해서 미리 SQL을 받아와서 사용함
executeQuery(), executeUpate()
executeQuery()Select문에서 사용
executeUpate() Insert, Delete문에서 사용
ResultSet
rs.next()
호출하면 커서가 다음으로 이동한다, 최초의 커서는 데이터를 가리키지 않음
rs.getString(), rs.getInt()
현재 커서가 가리키고 있는 컬럼의 값을 얻어온다 (타입지정)

Member - 생성

NOTE
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(); // sql 넣어주고 변수 삽입 pstmt = con.prepareStatement(sql); pstmt.setString(1, member.getMemberId()); pstmt.setInt(2, member.getMoney()); // 실행여부 int count = pstmt.executeUpdate(); return member; } catch (SQLException e) { log.error("db drror", e); throw e; } finally { close(con, pstmt, null); } }
Java
복사
Memer 생성코드

Member - 조회

NOTE
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 drror", e); throw e; } finally { close(con, pstmt, rs); } }
Java
복사
Memer 조회코드

Member - 추가

NOTE
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 drror", e); throw e; } finally { close(con, pstmt, null); } }
Java
복사
Memer 추가코드

Member - 삭제

NOTE
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 drror", e); throw e; } finally { close(con, pstmt, null); } }
Java
복사
Memer 삭제코드