0316_ex01_결과 1

– DB에 접속하여 CRUD 점수 관리를 해보자

성적 관리 스프레드시트 만들기

– 일련번호로 생성

– 총점, 평균, 순위를 표현하는 뷰 테이블 생성


테이블 정보

샘플 데이터

-- 시퀀스 생성
create sequence seq_scoretb_no;

-- 테이블 생성
create table SCORE (
	no NUMBER(3) primary key, -- 일련번호
	name VARCHAR2(50) not null, -- 이름
	kor NUMBER(3), -- 국어점수
	eng NUMBER(3), -- 영어점수
	mat NUMBER(3) -- 수학점수
);

-- 샘플데이터
insert into SCORE values(seq_scoretb_no.nextVal, '일길동', 77, 88, 99);
insert into SCORE values(seq_scoretb_no.nextVal, '이길동', 97, 98, 99);
insert into SCORE values(seq_scoretb_no.nextVal, '삼길동', 65, 76, 82);
commit;

-- 총점, 평균, 순위가 추가된 조회 view 생성
create or replace view SCORE_VIEW as
select s.*, (kor+eng+mat) total, round((kor+eng+mat)/3, 1) avg,
rank() over(order by (kor+eng+mat) DESC) rank
from (select * from SCORE) s order by no;

결과VO

– DB 값을 저장할 VO(Value Object) 클래스 생성

– 컬럼 이름이 같은 변수 선언

– 뷰 테이블에 정보를 보유해야 하므로 뷰 클래스에 모든 변수를 생성합니다.

package vo;

public class Ex01_ScoreVO {
	private int no, kor, eng, mat, total, rank;
	private String name;
	private float avg;
	
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	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 getMat() {
		return mat;
	}
	public void setMat(int mat) {
		this.mat = mat;
	}
	public int getTotal() {
		return total;
	}
	public void setTotal(int total) {
		this.total = total;
	}
	public float getAvg() {
		return avg;
	}
	public void setAvg(float avg) {
		this.avg = avg;
	}
	public int getRank() {
		return rank;
	}
	public void setRank(int rank) {
		this.rank = rank;
	}
} // end of class

ScoreDAO

1. DB에 연결하여 CRUD용 DAO(Data Access Object) 클래스 생성

2. _singleton으로 한번만 DB에 접속하도록 설정

– 생성자를 생성하고 비공개로 설정

– DB에 대한 다중 접근 방지

3. 공개 목록 선택목록() {}

1) 문자열 sql = “SELECT * FROM score_view”;

– score_view의 모든 데이터 쿼리

2) while 문으로 DB 정보를 vo 객체에 저장

4. public int 삽입(Ex01_ScoreVO vo) {}

1) 매개변수로 vo 객체를 받습니다.

2) 쿼리문을 sql 변수에 저장

– 점수 값(seq_scoretb_no.nextVal, ?, ?, ?, ?)에 삽입하여 쿼리 작성

– PreparedStatement 클래스로 할 수 있는 것은? vo에서 매개변수로 받은 정보를 할당합니다.

3) pstmt 매개변수 채우기

– pstmt.setString(1, vo.getName());

– pstmt.setInt(2, vo.getKor());

– vo의 변수 데이터 타입에 따라 설정해야 합니다.

– SQL로? 올바른 순서로 설정해야 합니다.

4) 성공적으로 삽입된 행의 수를 반환합니다.

5. 공개 int 삭제(int no) {}

1) 거기에 delete 쿼리 문에 넣을 수 있는 변수(여기서는 일련번호)를 파라미터로 받는다 –> 기본키를 받는 것을 추천한다.

2) 문자열 sql = “아니오 = ?인 점수에서 삭제”;

3) 지분과 논리는 동일합니다.

6. 공개 Int 업데이트(Ex01_ScoreVO vo) {}

1) 매개변수로 vo 객체를 받습니다.

2) 문자열 sql = “업데이트 스코어셋 이름 = ?, kor = ?, eng = ?, mat = ? WHERE no = ?”;

삼) pstmt 매개변수 채우기

– pstmt.setString(1, vo.getName());
– pstmt.setInt(2, vo.getKor());

4) 지분과 논리는 동일합니다.

package dao;

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

import service.DBService;
import vo.Ex01_ScoreVO;

public class Ex01_ScoreDAO {
	// single-ton pattern: 
	// 객체1개만생성해서 지속적으로 서비스하자
	static Ex01_ScoreDAO single = null;
	
	private Ex01_ScoreDAO() {

	} // end of constructor
	
	public static Ex01_ScoreDAO getInstance() {
		//생성되지 않았으면 생성
		if (single == null)
			single = new Ex01_ScoreDAO();
		//생성된 객체정보를 반환
		return single;
	} // end of getInstance()
	
	// SCORE 테이블 조회
	public List<Ex01_ScoreVO> selectList() {

		List<Ex01_ScoreVO> list = new ArrayList<Ex01_ScoreVO>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "SELECT * FROM score_view";

		try {
			//1.Connection얻어온다
			conn = DBService.getInstance().getConnection();
			//2.명령처리객체정보를 얻어오기
			pstmt = conn.prepareStatement(sql);

			//3.결과행 처리객체 얻어오기
			rs = pstmt.executeQuery();

			while (rs.next()) {
				Ex01_ScoreVO vo = new Ex01_ScoreVO();
				//현재레코드값=>Vo저장
				vo.setNo(rs.getInt("no"));
				vo.setName(rs.getString("name"));
				vo.setKor(rs.getInt("kor"));
				vo.setEng(rs.getInt("eng"));
				vo.setMat(rs.getInt("mat"));
				vo.setTotal(rs.getInt("total"));
				vo.setAvg(rs.getFloat("avg"));
				vo.setRank(rs.getInt("rank"));
				
				//ArrayList추가
				list.add(vo);
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {

			try {
				if (rs != null)
					rs.close();
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return list;
	} // end of selectList()
	
	// 성적 정보를 추가
	public int insert(Ex01_ScoreVO vo) {
		// TODO Auto-generated method stub
		int res = 0;

		Connection conn = null;
		PreparedStatement pstmt = null;
		
		// ?에 순서대로 값을 넣어줘야 한다.
		String sql = "insert into score values (seq_scoretb_no.nextVal, ?, ?, ?, ?)";

		try {
			//1.Connection획득
			conn = DBService.getInstance().getConnection();
			//2.명령처리객체 획득
			pstmt = conn.prepareStatement(sql);

			//3.pstmt parameter 채우기
			pstmt.setString(1, vo.getName());
			pstmt.setInt(2, vo.getKor());
			pstmt.setInt(3, vo.getEng());
			pstmt.setInt(4, vo.getMat());

			//4.DB로 전송(res:처리된행수)
			res = pstmt.executeUpdate(); // 성공한 행수가 반환됨, 다 실패했으면 0
			// res는 정수형 변수

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {

			try {
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return res;
	} // end of insert()
	
	// 학생정보 삭제
	public int delete(int no) {
		// TODO Auto-generated method stub
		int res = 0;

		Connection conn = null;
		PreparedStatement pstmt = null;

		String sql = "delete from score where no = ?";

		try {
			//1.Connection획득
			conn = DBService.getInstance().getConnection();
			//2.명령처리객체 획득
			pstmt = conn.prepareStatement(sql);

			//3.pstmt parameter 채우기
			pstmt.setInt(1, no);
			
			//4.DB로 전송(res:처리된행수)
			res = pstmt.executeUpdate();

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {

			try {
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return res;
	} // end of delete()
	
	public int update(Ex01_ScoreVO vo) {
		// TODO Auto-generated method stub
		int res = 0;

		Connection conn = null;
		PreparedStatement pstmt = null;

		String sql = "update score set name = ?, kor = ?, eng = ?, mat = ? WHERE no = ?";

		try {
			//1.Connection획득
			conn = DBService.getInstance().getConnection();
			//2.명령처리객체 획득
			pstmt = conn.prepareStatement(sql);

			//3.pstmt parameter 채우기
			pstmt.setString(1, vo.getName());
			pstmt.setInt(2, vo.getKor());
			pstmt.setInt(3, vo.getEng());
			pstmt.setInt(4, vo.getMat());
			pstmt.setInt(5, vo.getNo());
			
			//4.DB로 전송(res:처리된행수)
			res = pstmt.executeUpdate();

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {

			try {
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return res;
	} // end of update()
	
} // end of class