DB 연결
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection {
public static Connection getConnection() {
String url = "jdbc:mysql://localhost:3306/store";
String username = "root";
String password = "bitc5600!";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(url,username,password);
return conn;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
1. Store 클래스 정리
Store 클래스
- 역할:
DB
의store
테이블과 비슷한 구조를 가진 데이터 모델
- 기능: 상품의 ID, 이름, 가격, 수량을 저장하고 관리
package model;
// model -> DB에 있는 table 데이터를 비슷하게 구현한 것
public class Store {
private Integer id; // 상품 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;
}
// Getter 메서드 (데이터 조회)
public Integer getId() { return id; }
public String getName() { return name; }
public Integer getPrice() { return price; }
public Integer getQty() { return qty; }
// 객체 정보를 보기 쉽게 출력
@Override
public String toString() {
return "Store{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
", qty=" + qty +
'}';
}
}
✅ 정리
✔
Store
클래스는 DB의 store 테이블을 모델링한 클래스✔ 데이터 캡슐화 (
private
필드 + getter
제공)✔
toString()
을 오버라이드하여 객체 정보를 보기 쉽게 출력✔ Setter 없이 불변 객체로 활용 가능 (
id
, name
, price
, qty
변경 불가)2. StoreDAO 클래스 정리 (Java, Notion 스타일)
StoreDAO 클래스
- 역할: 데이터베이스(
store_tb
테이블)와 상호작용하는 DAO (Data Access Object)
- 기능:
한 건 조회
,전체 조회
,한 건 추가
,한 건 수정
,한 건 삭제
package dao;
import model.Store;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
// Data Access Object (DAO) - 데이터베이스와 상호작용
public class StoreDAO {
private Connection conn;
// DAO 생성자 (DB 연결 객체 받음)
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();
if (rs.next()) { // 조회 결과가 있으면 Store 객체 반환
return new Store(
rs.getInt("id"),
rs.getString("name"),
rs.getInt("price"),
rs.getInt("qty")
);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null; // 데이터가 없으면 null 반환
}
// 2️⃣ 전체 조회
public List<Store> 전체조회() {
List<Store> stores = 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()) { // 여러 개의 데이터 조회
stores.add(new Store(
rs.getInt("id"),
rs.getString("name"),
rs.getInt("price"),
rs.getInt("qty")
));
}
return stores;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 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) throw new RuntimeException("추가 실패");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 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) throw new RuntimeException("수정 실패");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 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) throw new RuntimeException("삭제 실패");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
✅ 정리
✔
StoreDAO
클래스는 데이터베이스와 상호작용하는 DAO✔
PreparedStatement
사용 → SQL 인젝션 방지✔ 예외 발생 시
RuntimeException
으로 감싸서 처리✔ CRUD 기능 구현
한건조회(int id)
→ 특정id
의 상품 조회
전체조회()
→ 모든 상품 조회
한건추가(String name, int price, int qty)
→ 상품 추가
한건수정(String name, int price, int qty, int id)
→ 상품 수정
한건삭제(int id)
→ 상품 삭제
3. storeApp 클래스 정리
storeApp.java
- 역할: DAO(
StoreDAO
)를 활용하여 데이터베이스와 직접 상호작용하는 애플리케이션
- 기능:
DB 연결
,한 건 조회
,추가
,수정
,삭제
,전체 조회
실행
import dao.StoreDAO;
import model.Store;
import java.sql.Connection;
import java.util.List;
public class storeApp {
public static void main(String[] args) {
// 1️⃣ DB 연결 (세션 생성)
Connection conn = DBConnection.getConnection();
// 2️⃣ DAO 객체 생성
StoreDAO dao = new StoreDAO(conn);
// 3️⃣ 한 건 조회 (id: 3)
Store store = dao.한건조회(3);
System.out.println(store);
// 4️⃣ 데이터 추가 ("감자", 가격 500, 수량 2000)
dao.한건추가("감자", 500, 2000);
// 5️⃣ 데이터 수정 ("감자", 가격 500, 수량 10000, id: 3)
dao.한건수정("감자", 500, 10000, 3);
// 6️⃣ 데이터 삭제 (id: 1)
dao.한건삭제(1);
// 7️⃣ 전체 조회
List<Store> stores = dao.전체조회();
for (Store s : stores) { // 변수명 중복 해결
System.out.println(s);
}
}
}
✅ 정리
✔
DBConnection.getConnection()
을 통해 데이터베이스 연결✔
StoreDAO
를 사용하여 CRUD 실행✔
for-each
문에서 store
변수가 중복 선언되어 s
로 변경 (⚠ 오류 해결)✔ 실행 순서
1️⃣ DB 연결
2️⃣
StoreDAO
객체 생성3️⃣ 특정 ID(3) 조회
4️⃣ "감자" 추가
5️⃣ "감자" 정보 수정
6️⃣ ID(1) 삭제
7️⃣ 전체 데이터 출력
Share article