[JAVA] 72. JDBC

문정준's avatar
Mar 05, 2025
[JAVA] 72. JDBC

사전 준비

  • New Project
    • Build System : Gradle (라이브러리를 관리하는 Language)
    • DSL : 도메인 관리 - Groovy
notion image
 
  • 패키지 및 파일 생성
notion image
 

Maven Repository

  • 각종 라이브러리 혹은 패키지 설치 페이지
notion image
 
  • ‘mysql’ 검색 후 MySQL Connector/J 클릭
notion image
 
  • 현재 설치된 MySQL 버전에 맞추어서, 버전 선택
    • 8.0.41이 설치되어 있으나, 이 버전과 맞는 패키지가 없어 8.0.33 설치
notion image
 
  • Gradle 클릭 후 아래 글 클릭 : 자동 복사
notion image
 
  • IntelliJ의 build.gradle에서 설치
notion image
 

1. DB 연결

  • mysql driver를 사용하여 Class.forName을 이용해 new Driver 객체 생성
  • DriverManager가 동적으로 이 객체를 찾아 드라이버를 사용 (Reflection)
import com.mysql.cj.jdbc.Driver; import com.mysql.cj.jdbc.JdbcConnection; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Scanner; public class StoreApp { public static void main(String[] args) { // protocol, username, password String url = "jdbc:mysql://localhost:3306/store"; String username = "root"; String password = "bitc5600!"; try { // 드라이버를 적어서 자동(동적)으로 heap에 올려두고, DriverManager가 Reflection을 통해 찾아냄 Class.forName("com.mysql.cj.jdbc.Driver"); Connection jdbc = DriverManager.getConnection(url, username, password); System.out.println("Connected to database"); } catch (Exception e) { throw new RuntimeException(e); } } }
 

결과

notion image
 
  • 아이디, 비밀번호가 틀릴 시 에러
notion image
 

리플렉션 (Reflection)

 

notion image
notion image
notion image
 

2. 버퍼 - PreparedStatement

1. DBConnection 클래스 생성

  • 연결을 main에서 하지 말고, 다른 클래스를 생성해서 끌어쓰기
import java.sql.Connection; import java.sql.DriverManager; public class DBConnection { public static Connection getConnection() { // protocol, username, password String url = "jdbc:mysql://localhost:3306/store"; String username = "root"; String password = "bitc5600"; try { // 드라이버를 적어서 자동(동적)으로 heap에 올려두고, DriverManager가 Reflection을 통해 찾아냄 Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection(url, username, password); System.out.println("Connected to database"); return conn; } catch (Exception e) { throw new RuntimeException(e); } } }
 

2. 버퍼 생성

  • PreparedStatement : SQL문을 전송하는 버퍼 (BufferedWriter)
import com.mysql.cj.jdbc.Driver; import com.mysql.cj.jdbc.JdbcConnection; import java.sql.*; import java.util.Scanner; public class StoreApp { public static void main(String[] args) { // 1. DB 연결 - 세션 만들어짐 Connection conn = DBConnection.getConnection(); try { // 2. 버퍼 String sql = "select id, name, price, qty from store_tb where id = ?"; PreparedStatement psmt = conn.prepareStatement(sql); psmt.setInt(1, Integer.valueOf(2)); ResultSet rs = psmt.executeQuery(); // 3. Projection int id; String name; int price; int qty; boolean isThere = rs.next(); // rs.next() : cursor 한 칸 내림 if (isThere) { id = rs.getInt("id"); name = rs.getString("name"); price = rs.getInt("price"); qty = rs.getInt("qty"); System.out.println(id + " " + name + " " + price + " " + qty); } } catch (SQLException e) { throw new RuntimeException(e); } } }
 
  • DB Setting
-- 1. root 접속 -- 2. DB 생성 CREATE DATABASE store; -- 3. store DB를 선택한다. use store; -- 4. 테이블 생성 및 더미데이터 세팅 CREATE TABLE store_tb( id int primary key auto_increment, name varchar(20), price int, qty int ); insert into store_tb(name, price, qty) values('사과', 1000, 50); insert into store_tb(name, price, qty) values('딸기', 2000, 50); commit;
 

DB 서비스 확인

  • DB 연결 시에는 현재 DBMS가 작동 중 (서비스 중)인지 확인해야 함
notion image
 

결과

notion image
 

한글 크래쉬 해결

  • Setting - ‘gradle’ 검색 후 run을 IntelliJ로 변경
notion image
 
notion image
notion image
 

3. Functioning - Model, DAO 사용

✏️

Model

  • DB에서 받아오는 데이터는 테이블 형태
  • 이를 자바에서 Projection을 통해 각기 다른 타입으로 뽑아와서 저장
  • 각기 다른 형태의 데이터를 효과적으로 저장할 수 있도록 Model 클래스 사용
    • DB에는 int도 null 데이터가 있지만, 자바는 int형에서 null을 받으면 0으로 변환
    • null로 저장할 수 있는 제네릭 클래스 Integer 사용
  • toString()을 통해 데이터 출력 형태 설정 가능
package model; // model - DB에 있는 Table 데이터를 비슷하게 구현 public class Store { // int -> Integer : DB에는 null 값도 존재하지만 int는 null을 0으로 바꿔버림 private Integer id; private String name; private Integer price; private Integer qty; public Store(Integer id, String name, Integer price, Integer qty) { this.id = id; this.name = name; this.price = price; this.qty = qty; } @Override public String toString() { return "Store { " + "id = " + id + ", name = '" + name + '\'' + ", price = " + price + ", qty = " + qty + " }"; } }
 
✏️

DAO (Data Access Object)

  • DB에 접근할 때 사용하는 객체
  • SEARCH, INSERT, UPDATE, DELETE 등 DML을 사용할 때에 호출하는 객체
  • 자바에서는 함수 형태로 제작하여 사용 가능
notion image
 

DAO 작성

  • SEARCH ( 한 건 탐색 )
package dao; import model.Store; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; // DAO (Data Access Object) : DB 데이터 접근 가능 객체 public class StoreDAO { private Connection conn; public StoreDAO(Connection conn) { this.conn = conn; } // 1. 한 건 조회 public Store 한건조회(int id) { try { String sql = "select id, name, price, qty from store_tb where id = ?"; PreparedStatement psmt = conn.prepareStatement(sql); psmt.setInt(1, id); ResultSet rs = psmt.executeQuery(); boolean isThere = rs.next(); // rs.next() : cursor 한 칸 내림 if (isThere) { Store model = new Store( rs.getInt("id"), rs.getString("name"), rs.getInt("price"), rs.getInt("qty") ); return model; } } catch (SQLException e) { throw new RuntimeException(e); } return null; }
  • SEARCHALL ( 전체 탐색 )
// 2. 전체 조회 // Business : 항상 최신 정보부터 조회 - For UX >> order by id desc public List<Store> 전체조회() { List<Store> models = new ArrayList<>(); try { String sql = "select * from store_tb order by id desc"; PreparedStatement psmt = conn.prepareStatement(sql); ResultSet rs = psmt.executeQuery(); while (rs.next()) { Store model = new Store( rs.getInt("id"), rs.getString("name"), rs.getInt("price"), rs.getInt("qty") ); models.add(model); } return models; } catch (Exception e) { throw new RuntimeException(e); } // throws로 인해 오류 발생 시 함수 자동 종료 => return null 필요 없음 }
  • INSERT ( 삽입 )
// 3. 한 건 추가 public void 한건추가(String name, int price, int qty) { try { String sql = "insert into store_tb (name, price, qty) values (?, ?, ?)"; PreparedStatement psmt = conn.prepareStatement(sql); psmt.setString(1, name); psmt.setInt(2, price); psmt.setInt(3, qty); int result = psmt.executeUpdate(); if (result > 0) System.out.println("Update Completed"); } catch (Exception e) { throw new RuntimeException(e); } }
  • UPDATE ( 수정 )
// 4. 한 건 수정 public void 한건수정(String name, int price, int qty, int id) { try { String sql = "update store_tb set name = ?, price = ?, qty = ? where id = ?"; PreparedStatement psmt = conn.prepareStatement(sql); psmt.setString(1, name); psmt.setInt(2, price); psmt.setInt(3, qty); psmt.setInt(4, id); int result = psmt.executeUpdate(); if (result > 0) System.out.println("Update Completed"); } catch (Exception e) { throw new RuntimeException(e); } }
  • DELETE ( 삭제 )
// 5. 한 건 삭제 public void 한건삭제(int id) { try { String sql = "delete from store_tb where id = ?"; PreparedStatement psmt = conn.prepareStatement(sql); psmt.setInt(1, id); int result = psmt.executeUpdate(); if (result > 0) System.out.println("Update Completed"); } catch (Exception e) { throw new RuntimeException(e); } } }
 

결과

  • SELECT
notion image
 
  • INSERT
notion image
notion image
  • UPDATE
notion image
notion image
  • DELETE
notion image
notion image
  • SELECTALL
notion image
Share article

sxias