[JSP & Servlet] 쇼핑몰 (오늘 본 상품 & 장바구니) - DAO

 

📌SQL 구문을 전송하는 클래스

ClothesDAO.java

package dao;

import static db.JdbcUtil.*;
import java.sql.*;
import java.util.ArrayList;
import vo.Clothes;

public class ClothesDAO {
	
	Connection con;
	private static ClothesDAO clothesDAO;
	
	private ClothesDAO() {
		
	}
	
	public void setConnection(Connection con){
		this.con = con;
	}
	
	public static ClothesDAO getInstance(){
		
		if(clothesDAO ==null){
			clothesDAO = new ClothesDAO();
		}
		
		return clothesDAO;
	}
	
	//상품 정보 리스트
	public ArrayList<Clothes> selectClothesList() {
		PreparedStatement pstmt = null;
		ResultSet rs= null;
		ArrayList<Clothes> clothesList = null;
		
		try {
			pstmt = con.prepareStatement("SELECT * FROM shop");
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				clothesList = new ArrayList<Clothes>();
				
				do {
					clothesList.add(new Clothes(
							rs.getInt("id")
							,rs.getString("name")
							,rs.getInt("price")
							,rs.getString("image")
							,rs.getString("size")
							,rs.getString("content")
							,rs.getInt("readcount")));
				} while (rs.next());
				
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(rs);
			close(pstmt);
		}
		
		return clothesList;
	}
	
	//상품 하나 선택
	public Clothes selectClothes(int id) {
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Clothes cloth = null;
		
		try {
			pstmt = con.prepareStatement("SELECT * FROM shop WHERE id=?");
			pstmt.setInt(1, id);
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				cloth = new Clothes(
						rs.getInt("id")
						,rs.getString("name")
						,rs.getInt("price")
						,rs.getString("image")
						,rs.getString("size")
						,rs.getString("content")
						,rs.getInt("readcount"));
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(pstmt);
			close(rs);
		}
		
		return cloth;
	}
	
	//조회수 증가
	public int updateReadCount(int id) {
		PreparedStatement pstmt = null;
		int updateCount = 0;
		String sql = "";
		
		try {
			sql = "UPDATE shop SET readcount = readcount + 1 WHERE id=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, id);
			updateCount = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(pstmt);
		}
		
		return updateCount;
	}
	
	//상품 넣기
	public int insertClothes(Clothes cloth) {
		PreparedStatement pstmt = null;
		int insertCount = 0;
		String sql = "";
		
		try {
			sql = "INSERT INTO shop VALUES(?,?,?,?,?,?)";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, cloth.getName());
			pstmt.setInt(2, cloth.getPrice());
			pstmt.setString(3, cloth.getImage());
			pstmt.setString(4, cloth.getSize());
			pstmt.setString(5, cloth.getContent());
			pstmt.setInt(6, cloth.getReadcount());
			insertCount = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(pstmt);
		}
		
		return insertCount;
	}
	
}