1. 더미 데이터 세팅
-- local - root 접속
create database store;
use store;
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;2. 조회 실습
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class StoreApp {
    public static void main(String[] args) {
        // 1. DB 연결 - 세션 만들어짐
        Connection conn = DBConnection.getConnection();
        // 2. 버퍼
        try {
            String sql = "select id, name, price, qty from store_tb where id = ?";
            PreparedStatement psmt = conn.prepareStatement(sql);
            psmt.setInt(1,2); // parameterIndex 1은 물음표의 위치
            // 3. flush (rs = table 조회 결과 즉 view)
            ResultSet rs = psmt.executeQuery();
            boolean isThere = rs.next(); // 커서 한 칸 내리기
            System.out.println("isThere : " + isThere);
            if (isThere) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int price = rs.getInt("price");
                int qty = rs.getInt("qty");
                System.out.println(id + " " + name + " " + price + " " + qty);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

3. MySQL과 자바를 연동하여 상품 프로그램 출력해보기(StoreApp)
1️⃣
package model;
// model -> db에 있는 table 데이터를 비슷하게 구현한 것
public class Store {
    private Integer id; // int 를 Integer로 바꾸기
    private String name;
    private Integer price; // 만약 mysql에서 hello_price 였을때 자바에서는 helloPrice (카멜표기법)로 표현한다
    private Integer qty;
    @Override
    public String toString() {
        return "Store{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", qty=" + qty +
                '}';
    }
    public Store(Integer id, String name, Integer price, Integer qty) { // 생성자 만들기
        this.id = id;
        this.name = name;
        this.price = price;
        this.qty = qty;
        
    }
    public Integer getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public Integer getPrice() {
        return price;
    }
    public Integer getQty() {
        return qty;
    }
}
2️⃣
import dao.StoreDAO;
import model.Store;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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. 한 건 조회
         Store model = dao.한건조회(2);
         System.out.println(model);
        // 4. 한건 추가
         dao.한건추가("감자", 500, 2000);
        // 5. 한건 수정
         dao.한건수정("감자", 500, 10000, 3);
        // 6. 한건 삭제
         dao.한건삭제(1);
        // 7. 전체 조회
        List<Store> models = dao.전체조회();
        // 포이츠
        for (Store model : models) {
            System.out.println(model);
        }
    }
}
3️⃣
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;
// Data Access Object
public class StoreDAO { // 커넥션에 의존해야 함
    private Connection conn;
    public StoreDAO(Connection conn) { // 생성자 만들기
        this.conn = conn;
    }
    // 1. 한 건 조회
    public Store 한건조회(int id) { // 무엇을 리턴 해야할지 모르겠다면 일단 void 써놓고 하기
        try {
            // 2. 버퍼
            String sql = "select id, name, price, qty from store_tb where id = ?";
            PreparedStatement psmt = conn.prepareStatement(sql);
            psmt.setInt(1, id); // parameterIndex 1은 물음표의 위치
            // 3. flush (rs = table 조회 결과 즉 view)
            ResultSet rs = psmt.executeQuery();
            boolean isThere = rs.next(); // 커서 한 칸 내리기
            if (isThere) {
                Store model = new Store(
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getInt("price"),
                        rs.getInt("qty")
                );
                return model;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    // 2. 전체 조회 - 전체조회는 기본적으로 순서를 거꾸로 조회함, 전체 조회의 책임 = 리턴 해서 전체조회 하는 것
    public List<Store> 전체조회() {
        List<Store> models = new ArrayList<Store>();
        try {
            String sql = "select * from store_tb order by id desc"; // desc로 받기, 화면으로 봤을 때 1~10 까지로 하면 10먼저 보여주는 것
            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); // 이 코드가 없으면 오류가 남
        }
    }
    // 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(); // write 할 때 씀 (insert, delete, update), 변경된 행의 갯수를 알 때
            if (result == 0) {
                throw new RuntimeException("insert가 안됐어");
            }
        } 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);
        }
    }
}
4️⃣ 결과
Share article




