Database 연동

Let's Just Go·2022년 5월 22일
0

JSP

목록 보기
5/12

JSP DATABASE 연동

  • Connection(연동)

    • oraclexe → app → oracle → product → 버전 → server → jdbc → lib → ojdbc6.jar 복사 후 WEB-INF의 lib에 붙여넣기

  • 11g version 설치
    - https://www.oracle.com/database/technologies/xe-prior-release-downloads.html

  • SQL Developer 설치

  • Terminal(SQL PLUS)

    • account unlock
    • hr계정 해제
    • alter user hr account unlock identified by hr;
    • connect hr;
    • ID : hr , PS : hr

  • SQL DEVELOPER
    - sqldeveloper.exe 실행

  • SQL DEVELOPER
    - sqldeveloper.exe 실행

  • 계정 생성
    - cmd에서 sqlplus접속
    - CREATE USER jsp IDENTIFIED BY jsp;
    - GRANT CREATE SESSION TO jsp;
    - GRANT CONNECT, RESOURCE TO jsp;
    - ALTER USER jsp DEFAULT TABLESPACE users QUOTA UNLIMITED ON users;

  • 접속 정보 등록(sql developer)
    - Name : jsp_practice
    - ID : jsp PW : jsp

Connection Example

Create Table

  • 테이블 생성

    • scores 테이블 생성

      CREATE TABLE scores (
          id    NUMBER PRIMARY KEY,
          name  VARCHAR2(30) NOT NULL,
          kor   NUMBER(3) DEFAULT 0,
          eng   NUMBER(3) DEFAULT 0,
          math  NUMBER(3) DEFAULT 0,
          total NUMBER(3) DEFAULT 0,
          avg   NUMBER(5, 2)
      );
      
      CREATE SEQUENCE id_seq 
      START WITH 1 INCREMENT BY 1 MAXVALUE 1000 NOCACHE NOCYCLE;

  • MODEL

    • DAO 클래스와 VO(value object) 클래스

    • DB에 접근하는 객체를 DAO 하나로만 접근하여 진행

DAO(Data Access Object)

  • DAO class
    • 데이터베이스에 접속해서 데이터의 추가, 삭제, 수정 등의 작업을 하는 클래스

    • 유지보수 및 코드의 모듈화를 위해 별도의 DAO 클래스를 만들어 사용

    • 보통 한 개의 테이블마다 한 개의 DAO 클래스를 작성

    • DAO를 구현하면 테이블의 컬럼과 매핑되는 값을 갖는 자바빈 클래스를 항상 작성해야 하며 자바빈 클래스를 VO 클래스라고 함

    • Singleton : 객체의 생성을 단 하나로 제한하기 위한 코드 디자인 패턴

      package kr.co.jsp.score.model;
      
      import java.sql.Connection;
      import java.sql.DriverManager;
      import java.sql.PreparedStatement;
      import java.sql.ResultSet;
      import java.sql.SQLException;
      
      import javax.sql.ConnectionEvent;
      
      // DAO는 웹 서버의 DB 연동 요청이 발생할 때 마다 
      // DB의 CRUD(Create, Read, Update, Delete)작업을 전담하는 클래스 
      public class ScoreDAO {	
      	// 싱글톤 디자인 패턴 (객체 생성을 단 하나로 제한하기 위한 코드 디자인 패턴)
      	
      	// 1. 클래스 외부에서 객체를 생성하지 못하게 생성자에 private 접근 제한을 붙임
      	private ScoreDAO() {
      		// DB와 객체를 전달할 수 있는 길 뚫어놓기 
      		try {
      			Class.forName("oracle.jdbc.driver.OracleDriver");
      		} catch (Exception e) {
      			// TODO Auto-generated catch block
      			e.printStackTrace();
      		}
      	}
      	
      	// 2. 이제 객체를 생성할 수 있는 영역은 해당 클래스 내부 뿐이므로 스스로 객체를 단 하나만 생성 
      	private static ScoreDAO dao = new ScoreDAO();
      	// 만든 객체를 전역으로 사용하기 위해 static으로 설정
      	// static이므로 외부에서 클래스의 객체에 바로 접근할 수 있는데 접근하지 못하도록 private로 해줌
      	
      	// 3. 외부에서 객체를 요구할 시 공개된 메서드를 통해 2번에서 미리 만들어 놓은 단 하나의 객체 주소값을 리턴 
      	// 만들어 놓은 객체만 돌려쓰기 위해 강제하는 작업
      	public static ScoreDAO getInstance() {
      		if (dao == null) {
      			dao = new ScoreDAO();
      		}
      		// 호옥시나 dao가 null일때를 대비해서 
      		
      		return dao;
      		// dao라는 객체를 getInstance()에서만 접근할 수 있도록 하기 위해 객체 생성을 static과 private을 활용하여 생성
      	}
      	
      	// ===================================================================================
      	
      	// DB관련 여러가지 작업 메서드가 들어가는 공간
      	Connection conn = null;
      	PreparedStatement pstmt = null;
      	ResultSet  rs = null;
      	
      	//모든 메서드에서 공용적으로 사용할 Connection 객체를 얻을 수 있는 유틸 메서드 
      	private Connection getConnection() throws Exception {
      		String url = "jdbc:oracle:thin:@localhost:1521:xe";
      		String uid = "jsp";
      		String upw = "jsp";
      		
      		return DriverManager.getConnection(url, uid, upw); 
      	}
      	
      	// 점수 데이터를 저장하는 메서드 
      	public boolean insert(ScoreVO vo) {
      // 점수를 저장한 객체들을 입력으로 받아 값을 데이터베이스에 넣어줌
      		boolean flag = false;
      		String sql = "INSERT INTO scores VALUES (id_seq.NEXTVAL, ?, ?, ?, ?, ?, ?)";
      		
      		try {
      			conn = getConnection();
      			pstmt = conn.prepareStatement(sql);
      			pstmt.setString(1,  vo.getName());
      			pstmt.setInt(2,  vo.getKor());
      			pstmt.setInt(3,  vo.getEng());
      			pstmt.setInt(4,  vo.getMath());
      			pstmt.setInt(5,  vo.getTotal());
      			pstmt.setDouble(6,  vo.getAvg());
      			// 값 넣어주기 
      			
      			int rn = pstmt.executeUpdate();
      			if (rn == 1) {
      				flag = true;
      			}
      		} catch (Exception e) {
      			// TODO Auto-generated catch block
      			e.printStackTrace();
      		} 
      		finally {
      			try {
      				pstmt.close();
      				conn.close();
      			} catch (SQLException e) {
      				e.printStackTrace();
      			}
      		}
      		return flag;
      	}
      }

VO(Value Object) or DTO(Data Transfer Object)

  • VO class or DTO(Data Transfer Object) class
    • DAO 클래스를 이용하여 DB에서 데이터를 관리할 때 데이터를 일반적인 변수에 할당하여 작업할 수도 있지만 별도의 VO 클래스를 작성하여 DB와 관련된 변수들의 모음 역할

    • VO 클래스는 자바빈 클래스로 생성

      package kr.co.jsp.score.model;
      
      /*
       CREATE TABLE scores (
          id    NUMBER PRIMARY KEY,
          name  VARCHAR2(30) NOT NULL,
          kor   NUMBER(3) DEFAULT 0,
          eng   NUMBER(3) DEFAULT 0,
          math  NUMBER(3) DEFAULT 0,
          total NUMBER(3) DEFAULT 0,
          avg   NUMBER(5, 2)
      );
      
      CREATE SEQUENCE id_seq 
      START WITH 1 INCREMENT BY 1 MAXVALUE 1000 NOCACHE NOCYCLE;
       */
      /**
       * @author MY
       *
       */
      public class ScoreVO {
      	// 자바빈 클래스란 데이터베이스와의 반복적인 작업을 쉽게 처리하기 위해 디자인하는 클래스
      	// 자바빈 클래스는 은닉(캡슐화)을 사용하여 설계
      	// 자바빈 클래스는 데이터베이스의 컬럼과 1:1로 매칭되는 멤버변수를 선언 
      	
      	private int id; 
      	private String name;
      	private int kor;
      	private int eng;
      	private int math;
      	private int total;
      	private double avg;
      	// DB의 컬럼이름과 일치하게 변수 선언 
      	// 자바빈 클래스는 일반적으로 기본 생성자(필수)와 모든 필드값을 매개값으로 받는 생성자(선택)를 하나씩 제작해줌 
      	
      	// 기본 생성자 
      	public ScoreVO() {
      		// TODO Auto-generated constructor stub
      	}
      	// 기본생성자 생성 단축키 : ctrl + space + enter
      	
      	
      	
      	// 매개변수를 받는 생성자 
      	public ScoreVO(int id, String name, int kor, int eng, int math, int total, double avg) {	
      		super();
      		this.id = id;
      		this.name = name;
      		this.kor = kor;
      		this.eng = eng;
      		this.math = math;
      		this.total = total;
      		this.avg = avg;
      	}
      	// 매개변수받는 생성자 생성 단축키 : alt + shift + s 
      
      	// getter setter 생성 단축키  : alt + shift + s
      	public int getId() {
      		return id;
      	}
      
      	public void setId(int id) {
      		this.id = id;
      	}
      
      	public String getName() {
      		return name;
      	}
      
      	public void setName(String name) {
      		this.name = name;
      	}
      
      	public int getKor() {
      		return kor;
      	}
      
      	public void setKor(int kor) {
      		this.kor = kor;
      	}
      
      	public int getEng() {
      		return eng;
      	}
      
      	public void setEng(int eng) {
      		this.eng = eng;
      	}
      
      	public int getMath() {
      		return math;
      	}
      
      	public void setMath(int math) {
      		this.math = math;
      	}
      
      	public int getTotal() {
      		return total;
      	}
      
      	public void setTotal(int total) {
      		this.total = total;
      	}
      
      	public double getAvg() {
      		return avg;
      	}
      
      	public void setAvg(double avg) {
      		this.avg = avg;
      	}
      }

    • insert_form

      <%@ page language="java" contentType="text/html; charset=UTF-8"
          pageEncoding="UTF-8"%>
      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="UTF-8">
      <title>Insert form</title>
      </head>
      <body>
      		<h1>시험점수 등록하기 </h1>
      		<form action="insert_controller.jsp" method = "post">
      		<!-- form안의 데이터를 POST형식으로  insert_controller에 보냄  -->
      		<p>
      		# 이름 : <input type = "text" name = "name" maxlength = "6"> <br>
      		# 국어점수 : <input type = "text" name = "kor" maxlength = "3"><br>
      		# 영어점수 : <input type = "text" name = "eng" maxlength = "3"><br>
      		# 수학점수 : <input type = "text" name = "math" maxlength = "3"><br>
      		<input type = "submit" value = "확인">
      		</p>
      		
      		
      		</form>
      </body>
      </html>

    • insert_form

      <%@ page language="java" contentType="text/html; charset=UTF-8"
          pageEncoding="UTF-8"%>
      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="UTF-8">
      <title>Insert form</title>
      </head>
      <body>
      		<h1>시험점수 등록하기 </h1>
      		<form action="insert_controller.jsp" method = "post">
      		<!-- form안의 데이터를 POST형식으로  insert_controller에 보냄  -->
      		<p>
      		# 이름 : <input type = "text" name = "name" maxlength = "6"> <br>
      		# 국어점수 : <input type = "text" name = "kor" maxlength = "3"><br>
      		# 영어점수 : <input type = "text" name = "eng" maxlength = "3"><br>
      		# 수학점수 : <input type = "text" name = "math" maxlength = "3"><br>
      		<input type = "submit" value = "확인">
      		</p>
      		
      		
      		</form>
      </body>
      </html>

    • insert_controller

      <%@page import="kr.co.jsp.score.model.ScoreDAO"%>
      <%@page import="kr.co.jsp.score.model.ScoreVO"%>
      <%@ page language="java" contentType="text/html; charset=UTF-8"
          pageEncoding="UTF-8"%>
      
          
          <%
          	request.setCharacterEncoding("utf-8");
          	String name = request.getParameter("name");
          	int kor = Integer.parseInt(request.getParameter("kor"));
          	int eng = Integer.parseInt(request.getParameter("eng"));
          	int math = Integer.parseInt(request.getParameter("math"));
          	// Integer.parseInt() : 문자열을 정수로 변환해주는 메소드
          	
          	int total = (kor + eng + math);
          	double avg = (total) / 3.0;
          	
          	// 데이터 포장 
          	ScoreVO vo = new ScoreVO(0, name, kor, eng, math, total, avg);
          	
          	ScoreDAO dao = ScoreDAO.getInstance();
          	// ScoreDAO의 주소값을 받아옴 (싱글톤이라서 하나의 객체만 생성하기 위해)
          	boolean flag = dao.insert(vo);
          	// vo로 저장된 객체를 줌
          	// 만약 데이터가 없으면 false로 들어감
          	
          	if (flag) {
          		response.sendRedirect("insert_success.jsp");
          	} else {
          		response.sendRedirect("insert_form.jsp");
          	}
          %>
profile
안녕하세요! 공부한 내용을 기록하는 공간입니다.

0개의 댓글