Day 37

·2023년 7월 27일
0

Global_2023_2

목록 보기
36/56

1. 아래를 프로그래밍 하시오.

  • DTO = dept Dto 클래스

    package edu.global.dto;
    
    /*
    -아래의 테이블 참고 Dept 테이블
    -
    이름     널?       유형           
    ------ -------- ------------ 
    DEPTNO NOT NULL NUMBER(2)    
    DNAME           VARCHAR2(14) 
    LOC             VARCHAR2(13) 
    */
    
    public class DeptDto {
        private int deptno;
        private String dname;
        private String loc;
    
      public DeptDto() {	
      }
    
      public DeptDto(int deptno, String dname, String loc) {
          this.deptno=deptno;
          this.dname=dname;
          this.loc=loc;
      }
    
      public int getDeptno() {
          return deptno;
      }
      public void setDeptno(int deptno) {
          this.deptno = deptno;
      }
      public String getDname() {
          return dname;
      }
      public void setDname(String dname) {
          this.dname = dname;
      }
      public String getLoc() {
          return loc;
      }
      public void setLoc(String loc) {
          this.loc = loc;
      }	
    	    }
  • DAO = dept Dao 클래스

    package edu.global.dao;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    import java.util.List;
    
    import edu.global.dto.DeptDto;
    
    public class DeptDao {
           private String driver ="oracle.jdbc.driver.OracleDriver";
            //오라클을 사용하므로 oracle드라이버를 넣어서 초기화
           private String url = "jdbc:oracle:thin:@localhost:1521:xe";
           private String uid = "scott";
           private String upw = "tiger";
            //DB에 접근하기 위해 id와 pw를 입력한다.
       
    	   public DeptDao() {
    		   try {
    			   Class.forName(driver);
    		
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    		}
    	   }
       
    	   public int deleteDept(int deptno) {
    	      
    		      Connection con = null;
    		      PreparedStatement stmt = null;
    		      String query = "delete from dept where deptno = ? "; 
    		      int result = 0;
    	      
    		      try {
    	         
    		         con = DriverManager.getConnection(url, uid, upw);
    		         stmt = con.prepareStatement(query);
    	         
    		         stmt.setInt(1, deptno);
    	         
    	         
    		         result = stmt.executeUpdate();
    
    		      } catch (Exception e) {
    		         e.printStackTrace();
    		      } finally {
    		         // ※제일 나중에 연거를 먼저 닫아줘야한다. Connection, Statement, ResultSet순서로
    		         // 열었으므로 거꾸로 닫아준다.
    		         try {
    	            
    		            if (stmt != null)
    		               stmt.close();
    		            if (con != null)
    		               con.close();
    
    		         } catch (Exception e2) {
    		            e2.printStackTrace();
    		         }
    		      }
    
    		      return result;
    
    		   }
       
       
    	   public int insertDept(int deptno, String dname, String loc) {
    	      
    		      Connection con = null;
    		      PreparedStatement stmt = null;
    		      String query = "insert into dept(deptno,dname,loc) values(?,?,?)"; 
    		      int result = 0;
    		      try {
    	         
    		         con = DriverManager.getConnection(url, uid, upw);
    		         stmt = con.prepareStatement(query);
    	         
    		         stmt.setInt(1, deptno);
    		         stmt.setString(2, dname);
    		         stmt.setString(3, loc);
    	         
    	         
    		         result = stmt.executeUpdate();
    
    		      } catch (Exception e) {
    		         e.printStackTrace();
    		      } finally {
    		         // ※제일 나중에 연거를 먼저 닫아줘야한다. Connection, Statement, ResultSet순서로
    		         // 열었으므로 거꾸로 닫아준다.
    		         try {
    	            
    		            if (stmt != null)
    		               stmt.close();
    		            if (con != null)
    		               con.close();
    
    		         } catch (Exception e2) {
    		            e2.printStackTrace();
    		         }
    		      }
    
    		      return result;
    
    		   }
    	   public List<DeptDto> getDepts(){
    		   //메모리에 연속된방을 잡는 ArrayList를 리턴타입으로 설정해준다.
    		   ArrayList<DeptDto> dtos = new ArrayList<DeptDto>();
    	   
    		   //Connection, Statement, ResultSte 3종세트를 순서대로 객체생성한다.
    		   //이때 import 할시 java.sql에 있는 인터페이스를 가져와야 한다(주의)
    		   Connection con = null;
    		   PreparedStatement stmt = null;
    		   ResultSet rs = null;
    	   
    		   try {
    			String query = "select * from dept"; //(가지고 오고자하는 쿼리문을 넣어준다)
    			//내 어플리케이션 오라클하고 접속(connection)
    			con = DriverManager.getConnection(url,uid,upw); 
    			// stmt = 빨대 = 커낵션객체에서 빨대 가져옴
    			stmt = con.prepareStatement(query);
    			//stmt.excuteQuery() = 채팅처럼 sql 구문을 엔터쳐서 전달
    			//결과를 ResultSet으로 받아옴
    			rs = stmt.executeQuery();
    		
    			while(rs.next()) {
    				int deptno = rs.getInt("deptno");
    				String dname = rs.getString("dname");
    				String loc = rs.getString("loc");
    			
    				DeptDto dto = new DeptDto(deptno,dname,loc);
    				dtos.add(dto);
    			}
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    		}finally {
    			try {
    				if (rs != null)
    					rs.close();
    				if (stmt != null)
    					stmt.close();
    				if (con != null)
    					con.close();
    			}
    			catch (Exception e){
    				e.printStackTrace();
    			}
    		}
    		   return dtos;
    	   }
    	}
  • dept_select.jsp ->dept 테이블에 있는 내용을 전부 유저에게 출력하여 보여주는 페이지

<%@page import="edu.global.dao.DeptDao"%>
<%@page import="edu.global.dto.DeptDto"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
	DeptDao dao = new DeptDao();

	dao.deleteDept(55);
	dao.deleteDept(66);

	List<DeptDto> dtos = dao.getDepts();
	
	//DeptDto dept = new DeptDto(55,"JAVA","Seoul");
	//dao.insertDept(dept.getDeptno(), dept.getDname(), dept.getLoc());
	
	//dept = new DeptDto(66,"JAVA","대구");
	//dao.insertDept(dept.getDeptno(), dept.getDname(), dept.getLoc());
	
	for(DeptDto dto : dtos){
		out.print("부서번호: " + dto.getDeptno()+
			"직종 이름: " + dto.getDname()+
			"지역: " + dto.getLoc()+"<br>");
	}
    %>
    </body>
    </html>

2. 아래의 개념을 설명하시오.

  • DAO

    데이터베이스와 통신하여 데이터를
    조회, 수정, 삭제하는 기능을 제공

  • DTO

    데이터베이스에서 조회한 데이터를 저장하고,
    웹 애플리케이션에 전달하는 기능을 제공

3. 아래의 3종 세트를 설명하시오.

  • Connetion

    데이터베이스 서버에 연결

  • Statement

    데이터베이스 서버에 SQL문을 전송

  • Resultset

    SQL문의 실행 결과를 반환

4. Statement객체에 두함수의 용도는?

  • executeQuery() :

    SELECT 문과 같은 질의문을 실행하는 데 사용

  • executeUpdate() :

    INSERT, UPDATE, DELETE 문과 같은 DML 문과 같은 DML문을 실행하는 데 사용


일단 게시판 짤 줄 알면 일 할 준비가 되었다고 믿고 쓴다✔


Point

  • 강제,규약,표준 interface driver로 여러 sql을 사용 가능

    • JDBC: java data base connection
  • 서버가 터진다: DB에서 터진다

    • 죽는 포인트

    • 부하를 방지하는 커넥션풀(CP): 미리 커넥션 개체를 만들어 놓는다

      • 미리 빨대를 꼽아 놓는것
  • 내장객체

    • 4개의 메모리 공간에 성질이 다르다
    • request: 포워딩까지 유지
      session: tomcat이 지정하는 시간까지(1800초)
      어플리케이션: 어플리케이션이 끝날때까지 유지

0개의 댓글