Notice
Recent Posts
Recent Comments
Link
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
Tags
more
Archives
Today
Total
관리 메뉴

WON.dev

GreenDao 본문

JSP/DB (3)

GreenDao

GAWON 2023. 6. 1. 09:20
package org.joonzis.ex;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class GreenDao {
   // 필드
   private Connection conn = null;
   private PreparedStatement ps = null;
   private ResultSet rs = null;
   private String sql = "";
   
   // 싱글톤
   private GreenDao() {}   // 기본 생성자(외부에서 접근할 수 없게 private 처리)
   private static GreenDao dao = new GreenDao();
   public static GreenDao getInstance() {
      return dao;
   }
   
   // 1. DB와 연결하기
   // 이 클래스 안에서 참고하겠다(DAO에서 모든 내용 처리, 메소드화)
   private Connection getConnection() {
      try {
         Class.forName("oracle.jdbc.driver.OracleDriver");
         String user = "scott";
         String password = "tiger";
         String url = "jdbc:oracle:thin:@localhost:1521:xe";
         conn = DriverManager.getConnection(url, user, password);
      } catch (Exception e) {
         e.printStackTrace();
      }
      return conn;
   }
   
   // DTO 여러개면 배열로(select * 해서 테이블 구조이면)
   // List<GreenDto> : 자바 빈 형태의 리스트
   // id 검색해서 데이터 하나만 나오면 List<GreenDto> 말고 그냥 GreenDto 사용(update, delete 등)
   // 2. 테이블의 전체 목록을 가져오는 메소드
   public List<GreenDto> getAllList() {
      List<GreenDto> list = new ArrayList<>();
      
      try {
         conn = getConnection();
         sql = "select * from green order by idx";
         ps = conn.prepareStatement(sql);
         rs = ps.executeQuery();      // rs : 임시 데이터 저장 공간
         
         while(rs.next()) {
            GreenDto dto = new GreenDto();
            dto.setIdx(rs.getInt(1));
            dto.setId(rs.getString(2));
            dto.setPw(rs.getString(3));
            dto.setName(rs.getString(4));
            dto.setAge(rs.getInt(5));
            dto.setAddr(rs.getString(6));
            dto.setReg_date(rs.getDate(7));
            list.add(dto);
         }
         
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
               if (rs != null) {
                  rs.close();
               }
               if (ps != null) {
                  ps.close();
               }
               if (conn != null) {
                  conn.close();
               }
      
            } catch (Exception e2) {
               e2.printStackTrace();
            }
      }
      
      return list;
   }
   
   // 데이터 삽입 메소드(뷰에서 삽입할 데이터 매개변수로)
   // 성공하거나 실패하거나 무조건 int 값 넘어와야함(문제 없을 때 void도 가능)
   public int getInsert(GreenDto dto) {
      int result = 0;
      
      try {
         conn = getConnection();

         String sql = "insert into green" + " values(green_seq.nextval, ?, ?, ?, ?, ?, sysdate)";
         ps = conn.prepareStatement(sql);
         conn.setAutoCommit(false); // 자동 커밋 방지
         
         
         ps.setString(1, dto.getId());
         ps.setString(2, dto.getPw());
         ps.setString(3, dto.getName());
         ps.setInt(4, dto.getAge());
         ps.setString(5, dto.getAddr());
         
         result = ps.executeUpdate();
         if (result > 0) {
            conn.commit();   // insert 잘 성공하면 커밋
         }   
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            if (ps != null) {
               ps.close();
            }
            if (conn != null) {
               conn.close();
            }
         } catch (Exception e2) {
            e2.printStackTrace();
         }
      }
      
      return result;
   }
   
   
   // 데이터 삭제 메소드
   // public int getRemove(String id, String pw) {}
   public int getRemove(GreenDto dto) {
      int result = 0;      // try 안 타면 그냥 result 0 return
      
      try {
         conn = getConnection();

         String sql = "delete from green where id=? and pw=?";
         ps = conn.prepareStatement(sql);
         conn.setAutoCommit(false); // 자동 커밋 방지
         
         ps.setString(1, dto.getId());
         ps.setString(2, dto.getPw());
         
         result = ps.executeUpdate();
         if (result > 0) {
            conn.commit();
         }   
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            if (ps != null) {
               ps.close();
            }
            if (conn != null) {
               conn.close();
            }
         } catch (Exception e2) {
            e2.printStackTrace();
         }
      }
      
      return result;
   }
   
   
   // 데이터 수정 메소드
   public int getUpdate(GreenDto dto) {
      int result = 0;
      
      try {
         conn = getConnection();

         String sql = "update green set pw=?, name=?, age=?, addr=? where idx=?";
         ps = conn.prepareStatement(sql);
         conn.setAutoCommit(false); // 자동 커밋 방지
         
         ps.setString(1, dto.getPw());
         ps.setString(2, dto.getName());
         ps.setInt(3, dto.getAge());
         ps.setString(4, dto.getAddr());
         ps.setInt(5, dto.getIdx());
         
         result = ps.executeUpdate();
         if (result > 0) {
            conn.commit();
         }   
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            if (ps != null) {
               ps.close();
            }
            if (conn != null) {
               conn.close();
            }
         } catch (Exception e2) {
            e2.printStackTrace();
         }
      }
      
      return result;
   }
   
   // 데이터 1개 출력
   public GreenDto getSelectOne(String id) {
      GreenDto dto = null;   // 데이터 즉, rs가 없으면 null
      
      try {
         conn = getConnection();
         sql = "select * from green where id=?";
         ps = conn.prepareStatement(sql);
         ps.setString(1, id);   // 쿼리 작동하기 전에 id=?에 전달받아온 매개변수 넣어줌
         rs = ps.executeQuery();   // 실제 쿼리 작동
         
         // if(rs.next()) : 데이터 있으면 담고 없으면 X
         if(rs.next()) {    // 행 기준, if문이나 while문 있어야 데이터 보여줌 
            dto = new GreenDto();
            dto.setIdx(rs.getInt("idx"));
            dto.setId(rs.getString(2));
            dto.setPw(rs.getString(3));
            dto.setName(rs.getString(4));
            dto.setAge(rs.getInt(5));
            dto.setAddr(rs.getString(6));
            dto.setReg_date(rs.getDate(7));   
         }

      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
               if (rs != null) {
                  rs.close();
               }
               if (ps != null) {
                  ps.close();
               }
               if (conn != null) {
                  conn.close();
               }
      
            } catch (Exception e2) {
               e2.printStackTrace();
            }
      }
      
      return dto;
   }
   
   
   // 업데이트를 위한 유저 정보 메소드
   public GreenDto getUpdateView(GreenDto dto) {
      GreenDto returnDto = null;
      
      try {
         conn = getConnection();
         sql = "select * from green where id=? and pw=?";
         ps = conn.prepareStatement(sql);
         ps.setString(1, dto.getId());
         ps.setString(2,  dto.getPw());
         rs = ps.executeQuery(); // 실제 쿼리 작동
         
         if (rs.next()) {
            returnDto = new GreenDto();
            returnDto.setIdx(rs.getInt(1));
            returnDto.setId(rs.getString(2));
            returnDto.setPw(rs.getString(3));
            returnDto.setName(rs.getString(4));
            returnDto.setAge(rs.getInt(5));
            returnDto.setAddr(rs.getString(6));
            returnDto.setReg_date(rs.getDate(7));
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
               if (rs != null) {
                  rs.close();
               }
               if (ps != null) {
                  ps.close();
               }
               if (conn != null) {
                  conn.close();
               }
      
            } catch (Exception e2) {
               e2.printStackTrace();
            }
      }
      
      return returnDto;
   }
}

'JSP > DB (3)' 카테고리의 다른 글

Remove  (0) 2023.06.01
Insert  (0) 2023.06.01
index  (0) 2023.06.01
GreenDto  (0) 2023.06.01
01_DTO_DAO_singleton  (0) 2023.05.24