kr.s08.score
생성하고 table.sql
생성CREATE TABLE score(
num NUMBER PRIMARY KEY,
name VARCHAR2(30) NOT NULL,
korean NUMBER(3) NOT NULL,
english NUMBER(3) NOT NULL,
math NUMBER(3) NOT NULL,
sum NUMBER(3) NOT NULL,
avg NUMBER(3) NOT NULL,
grade VARCHAR2(2) NOT NULL,
reg_date DATE NOT NULL
);
CREATE SEQUENCE score_seq;
ScoreVO
생성package kr.s08.score;
import java.sql.Date; // 데이터베이스와 연동하여 날짜 표시하는 경우에 사용; java.util.Date는 데이터베이스와 연동하지 않는 경우에 사용
public class ScoreVO {
// 은닉화
private int num; // 번호
private String name; // 이름
private int korean; // 국어
private int english; // 영어
private int math; // 수학
private int sum; // 총점
private int avg; // 평균
private String grade; // 등급
private Date reg_date; // 등록일
// 캡슐화
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getKorean() {
return korean;
}
public void setKorean(int korean) {
this.korean = korean;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
public int getAvg() {
return avg;
}
public void setAvg(int avg) {
this.avg = avg;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public Date getReg_date() {
return reg_date;
}
public void setReg_date(Date reg_date) {
this.reg_date = reg_date;
}
// 총점 구하기
public int makeSum() {
return korean + english + math;
}
// 평균 구하기
public int makeAvg() {
return makeSum()/3;
}
// 등급 구하기
public String makeGrade() {
String grade;
switch(makeAvg()/10) {
case 10:
case 9: grade = "A"; break;
case 8: grade ="B"; break;
case 7: grade = "C"; break;
case 6: grade = "D"; break;
default: grade = "F";
}
return grade;
}
}
ScoreDAO
생성package kr.s08.score;
import kr.s03.preparedstatement.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class ScoreDAO {
// 성적 입력
public void insertInfo(ScoreVO score) {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = null;
try {
// JDBC 수행 1,2단계
conn = DBUtil.getConnection();
// SQL문 작성
sql = "INSERT INTO score (num, name, korean, english, math, sum, avg, grade, reg_date) "
+ "VALUES (score_seq.NEXTVAL, ?, ?, ?, ?, ?, ?, ?, SYSDATE)";
// JDBC 수행 3단계 : PreparedStatement 객체 생성
pstmt = conn.prepareStatement(sql);
// ?에 데이터를 바인딩
pstmt.setString(1, score.getName());
pstmt.setInt(2, score.getKorean());
pstmt.setInt(3, score.getEnglish());
pstmt.setInt(4, score.getMath());
pstmt.setInt(5, score.makeSum());
pstmt.setInt(6, score.makeAvg());
pstmt.setString(7, score.makeGrade());
// JDBC 수행 4단계 : SQL문을 실행해서 테이블에 행을 삽입
int count = pstmt.executeUpdate();
if(count==1) System.out.println("성적 입력을 완료하였습니다.");
else System.out.println("성적 입력에 실패하였습니다.");
}
catch(Exception e) {
e.printStackTrace();
}
finally {
// 자원 정리
DBUtil.executeClose(null, pstmt, conn);
}
}
// 목록 보기
public void selectListInfo() {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
try {
// JDBC 수행 1,2단계
conn = DBUtil.getConnection();
// SQL문 작성
sql = "SELECT * FROM score ORDER BY num DESC";
// JDBC 수행 3단계 : PreparedStatement 객체 생성
pstmt = conn.prepareStatement(sql);
// JDBC 수행 4단계 : SQL문을 실행해서 테이블에서 결과 집합을 얻어 ResultSet에 담아서 반환
rs = pstmt.executeQuery();
System.out.println("총 자료 수 : " + getCountInfo());
System.out.println("번호\t이름\t국어\t영어\t수학\t총점\t평균\t등급");
while(rs.next()) {
System.out.print(rs.getInt("num") + "\t");
System.out.print(rs.getString("name") + "\t");
System.out.print(rs.getInt("korean") + "\t");
System.out.print(rs.getInt("english") + "\t");
System.out.print(rs.getInt("math") + "\t");
System.out.print(rs.getInt("sum") + "\t");
System.out.print(rs.getInt("avg") + "\t");
System.out.println(rs.getString("grade"));
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
// 자원 정리
DBUtil.executeClose(rs, pstmt, conn);
}
}
// 레코드 총 수
public int getCountInfo() {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
int count = 0;
try {
// JDBC 수행 1,2단계
conn = DBUtil.getConnection();
// SQL문 작성
sql = "SELECT COUNT(num) FROM score";
// JDBC 수행 3단계 : PreparedStatement 객체 생성
pstmt = conn.prepareStatement(sql);
// JDBC 수행 4단계 : SQL문을 실행해서 테이블의 총 레코드 수를 구해서 반환
rs = pstmt.executeQuery();
if(rs.next()) {
count = rs.getInt(1);
} // rs에 행이 없는 경우 count는 기본값이 반환됨
}
catch(Exception e) {
e.printStackTrace();
}
finally {
// 자원 정리
DBUtil.executeClose(rs, pstmt, conn);
}
return count;
}
// 상세 정보 보기
public int selectDetailInfo(int num) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
int exitcode = 0;
try {
// JDBC 수행 1,2단계
conn = DBUtil.getConnection();
// SQL문 작성
sql = "SELECT * FROM score WHERE num=?";
// JDBC 수행 3단계 : PreparedStatement 객체 생성
pstmt = conn.prepareStatement(sql);
// ?에 데이터를 바인딩
pstmt.setInt(1, num);
// JDBC 수행 4단계 : SQL문을 실행해서 테이블로부터 결과 행을 얻고 ResultSet에 담아서 반환
rs = pstmt.executeQuery();
if(rs.next()) {
System.out.println("번호 : " + rs.getInt("num"));
System.out.println("이름 : " + rs.getString("name"));
System.out.printf("국어 : %3d\t영어 : %3d\t수학 : %3d%n", rs.getInt("korean"), rs.getInt("english"), rs.getInt("math"));
System.out.printf("총점 : %3d\t평균 : %3d\t등급 : %3s%n", rs.getInt("sum"), rs.getInt("avg"), rs.getString("grade"));
System.out.println("입력일 : " + rs.getString("reg_date"));
exitcode = 1;
}
else {
System.out.println(num + "번에 해당하는 자료가 없습니다.");
exitcode = -1;
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
// 자원 정리
DBUtil.executeClose(rs, pstmt, conn);
}
return exitcode;
}
// 수정
public void updateInfo(ScoreVO score) {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = null;
try {
// JDBC 수행 1,2단계
conn = DBUtil.getConnection();
// SQL문 작성
sql = "UPDATE score SET name=?, korean=?, english=?, math=?, sum=?, avg=?, grade=? WHERE num=?";
// JDBC 수행 3단계 : PreparedStatement 객체 생성
pstmt = conn.prepareStatement(sql);
// ?에 데이터를 바인딩
pstmt.setString(1, score.getName());
pstmt.setInt(2, score.getKorean());
pstmt.setInt(3, score.getEnglish());
pstmt.setInt(4, score.getMath());
pstmt.setInt(5, score.makeSum());
pstmt.setInt(6, score.makeAvg());
pstmt.setString(7, score.makeGrade());
pstmt.setInt(8, score.getNum());
// JDBC 수행 4단계 : SQL문을 실행해서 테이블의 행 정보를 갱신
int count = pstmt.executeUpdate();
if(count==1) System.out.println(score.getNum() + "번에 해당하는 자료를 수정하였습니다.");
else System.out.println(score.getNum() + "번에 해당하는 자료를 수정하지 못했습니다!");
}
catch(Exception e) {
e.printStackTrace();
}
finally {
// 자원 정리
DBUtil.executeClose(null, pstmt, conn);
}
}
// 삭제
public void deleteInfo(int num) {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = null;
try {
// JDBC 수행 1,2단계
conn = DBUtil.getConnection();
// SQL문 작성
sql = "DELETE FROM score WHERE num=?";
// JDBC 수행 3단계 : PreparedStatement 객체 생성
pstmt = conn.prepareStatement(sql);
// ?에 데이터를 바인딩
pstmt.setInt(1, num);
// JDBC 수행 4단계 : SQL문을 실행해서 테이블의 행을 삭제
int count = pstmt.executeUpdate();
if(count==1) System.out.println(num + "번에 해당하는 자료를 삭제하였습니다.");
else System.out.println(num + "번에 해당하는 자료를 삭제하지 못했습니다!");
}
catch(Exception e) {
e.printStackTrace();
}
finally {
// 자원 정리
DBUtil.executeClose(null, pstmt, conn);
}
}
}
ScoreValueException
생성package kr.s08.score;
// 사용자 정의 예외 클래스
public class ScoreValueException extends Exception {
public ScoreValueException(String message) {
super(message);
}
}
ScoreMain
생성package kr.s08.score;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class ScoreMain {
private BufferedReader br;
private ScoreDAO dao;
public ScoreMain() {
dao = new ScoreDAO();
try {
br = new BufferedReader(new InputStreamReader(System.in));
callMenu();
}
catch(IOException e) {
e.printStackTrace();
}
finally {
if(br!=null) try {br.close();} catch(IOException e) {}
}
}
public void callMenu() throws IOException {
while(true) {
System.out.println("메뉴 : 1. 성적 입력, 2. 목록 보기, 3. 상세 정보 보기, 4. 수정, 5. 삭제, 6. 종료");
System.out.print("메뉴 > ");
try {
int menu = Integer.parseInt(br.readLine());
if(menu==1) { // 성적 입력
System.out.print("이름 > ");
String name = br.readLine();
int korean = parseInputData("국어 > ");
int english = parseInputData("영어 > ");
int math = parseInputData("수학 > ");
// ScoreVO 객체 생성
ScoreVO score = new ScoreVO();
score.setName(name);
score.setKorean(korean);
score.setEnglish(english);
score.setMath(math);
dao.insertInfo(score);
}
else if(menu==2) { // 목록 보기
dao.selectListInfo();
}
else if(menu==3) { // 상세 정보 보기
dao.selectListInfo(); // 번호 확인용 목록 보기
System.out.println("상세 정보를 조회할 자료의 번호를 입력하세요.");
System.out.print("번호 > ");
int num = Integer.parseInt(br.readLine());
dao.selectDetailInfo(num);
}
else if(menu==4) { // 수정
dao.selectListInfo(); // 번호 확인용 목록 보기
System.out.println("수정할 자료의 번호를 입력하세요.");
System.out.print("번호 > ");
int num = Integer.parseInt(br.readLine());
if(dao.selectDetailInfo(num)==-1) continue; // 수정할 글 번호를 잘못 입력한 경우 메뉴로 돌아감
ScoreVO score = new ScoreVO();
score.setNum(num);
System.out.print("이름 > ");
score.setName(br.readLine());
score.setKorean(parseInputData("국어 > "));
score.setEnglish(parseInputData("영어 > "));
score.setMath(parseInputData("수학 > "));
dao.updateInfo(score);
}
else if(menu==5) { // 삭제
System.out.print("삭제 전 ");
dao.selectListInfo(); // 번호 확인용 목록 보기
System.out.println("삭제할 자료의 번호를 입력하세요.");
System.out.print("번호 > ");
int num = Integer.parseInt(br.readLine());
dao.deleteInfo(num);
System.out.print("삭제 후 ");
dao.selectListInfo(); // 행 삭제가 정상적으로 수행되었는지 확인하기 위한 목록 보기
}
else if(menu==6) { // 종료
System.out.println("프로그램을 종료합니다.");
break;
}
else {
System.out.println("메뉴를 잘못 입력했습니다!");
}
}
catch(NumberFormatException e) {
System.out.println("숫자만 입력 가능합니다!");
}
}
}
// 성적 범위 검사(0~100)
public int parseInputData(String course) throws IOException {
while(true) {
System.out.println(course);
try {
int num = Integer.parseInt(br.readLine());
if(num<0 || num>100)
throw new ScoreValueException("0부터 100 사이의 값만 허용됩니다!");
return num;
}
catch(NumberFormatException e) {
System.out.println("숫자만 입력 가능합니다!");
}
catch(ScoreValueException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) {
new ScoreMain();
}
}