[28일차] JDBC - 성적 입출력 프로그램

SOSO·2022년 5월 25일
0

학원

목록 보기
26/59
post-thumbnail

🏆 성적 입출력 프로그램

DAO 클래스

DAO :
Data Access Object
데이터베이스의 데이터를 전문적으로 호출하고 제어하는 객체

package kr.s08.score;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import kr.s03.preparedstatement.DBUtil;

public class ScoreDAO {
	// 성적입력
	public void insertInfo(String name, int korean, int english, int math, int sum, int avg, String grade) {
		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딘계
			pstmt = conn.prepareStatement(sql);

			// ?에 데이터 바인딩
			pstmt.setString(1, name);
			pstmt.setInt(2, korean);
			pstmt.setInt(3, english);
			pstmt.setInt(4, math);
			pstmt.setInt(5, sum);
			pstmt.setInt(6, avg);
			pstmt.setString(7, grade);

			// JDBC 수행 4단계
			int count = pstmt.executeUpdate();
			System.out.println(count + "개의 행을 추가했습니다.");

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 자원정리
			DBUtil.executeClose(null, pstmt, conn);
		}
	}

	// 목록보기
	public void selectInfo() {
		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단계
			pstmt = conn.prepareStatement(sql);
			// JDBC 수행 4단계
			rs = pstmt.executeQuery();

			System.out.println("---------------------------------------");
			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") + "\t");
			}
			System.out.println("---------------------------------------");

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.executeClose(rs, pstmt, conn);
		}

	}

	// 성적상세보기
	public void selectDetailInfo(int num) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;

		try {
			// JDBC 수정 1,2 단계
			conn = DBUtil.getConnection();
			// SQL문 작성
			sql = "SELECT * FROM score WHERE num=?";

			// JDBC 수행 3단계
			pstmt = conn.prepareStatement(sql);
			// ?에 데이터 바인딩
			pstmt.setInt(1, num);

			// JDBC 수행 4단계
			rs = pstmt.executeQuery();
			// 출력 내용(번호,이름,국어,영어,수학,총점,평균,등급,등록일)
			if (rs.next()) {
				System.out.println("번호 : " + rs.getInt("num"));
				System.out.println("이름 : " + rs.getString("name"));
				System.out.println("국어 : " + rs.getInt("korean"));
				System.out.println("영어 : " + rs.getInt("english"));
				System.out.println("수학 : " + rs.getInt("math"));
				System.out.println("총점 : " + rs.getInt("sum"));
				System.out.println("평균 : " + rs.getInt("avg"));
				System.out.println("등급 : " + rs.getString("grade"));
				System.out.println("등록일 : " + rs.getDate("reg_date"));
			} else {
				System.out.println("검색된 정보가 없습니다.");
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 자원정리
			DBUtil.executeClose(rs, pstmt, conn);
		}
	}

	// 성적수정
	public void updateInfo( int num, String name, int korean, int english, int math, int sum, int avg, String grade) {
		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단계
			pstmt = conn.prepareStatement(sql);
			// ?에 데이터 바인딩
			pstmt.setString(1, name);
			pstmt.setInt(2, korean);
			pstmt.setInt(3, english);
			pstmt.setInt(4, math);
			pstmt.setInt(5, sum);
			pstmt.setInt(6, avg);
			pstmt.setString(7, grade);
			pstmt.setInt(8, num);

			// JDBC 수행 4단계
			int count = pstmt.executeUpdate();

			System.out.println(count + "개의 행을 수정했습니다.");

		} 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단계
			pstmt = conn.prepareStatement(sql);
			//?에 데이터 바인딩
			pstmt.setInt(1, num);
			
			//JDBC 수행 4단계
			int count = pstmt.executeUpdate();
			System.out.println(count + "개의 행을 삭제했습니다.");
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			//자원정리
			DBUtil.executeClose(null, pstmt, conn);
		}
	}

}

package kr.s08.score;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

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();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 자원정리
			if (br != null)
				try {
					br.close();
				} catch (IOException e) {
				}
		}
	}

	// 메뉴
	public void callMenu() throws IOException {
		while (true) {
			System.out.print("1.입력,2.목록,3.상세정보,4.수정,5.삭제," + "6.종료>");
			try {
				int no = Integer.parseInt(br.readLine());
				if (no == 1) { // 입력
					// 이름 입력
					System.out.print("이름:");
					String name = br.readLine();
					// 국어 입력
					int korean = parseInputData("국어: ");
					// 영어 입력
					int english = parseInputData("영어: ");
					// 수학 입력
					int math = parseInputData("수학: ");
					// 총점
					int sum = makeSum(korean, english, math);
					// 평균
					int avg = makeAvg(sum);
					// 등급
					String grade = makeGrade(avg);
					// 테이블에 데이터 입력
					dao.insertInfo(name, korean, english, math, sum, avg, grade);

				} else if (no == 2) { // 목록
					dao.selectInfo();

				} else if (no == 3) { // 상세정보
					System.out.print("선택한 글의 번호:");
					int num = Integer.parseInt(br.readLine());
					dao.selectDetailInfo(num);
				} else if (no == 4) { // 수정
					dao.selectInfo();

					System.out.print("수정할 글의 번호:");
					int num = Integer.parseInt(br.readLine());

					// 이름 입력
					System.out.print("이름:");
					String name = br.readLine();
					// 국어 입력
					int korean = parseInputData("국어: ");
					// 영어 입력
					int english = parseInputData("영어: ");
					// 수학 입력
					int math = parseInputData("수학: ");
					// 총점
					int sum = makeSum(korean, english, math);
					// 평균
					int avg = makeAvg(sum);
					// 등급
					String grade = makeGrade(avg);

					dao.updateInfo(num, name, korean, english, math, sum, avg, grade);

				} else if (no == 5) { // 삭제
					dao.selectInfo();

					System.out.print("삭제할 글의 번호:");
					int del_num = Integer.parseInt(br.readLine());

					dao.deleteInfo(del_num);

				} else if (no == 6) { // 종료
					System.out.println("프로그램을 종료합니다.");
					break;
				} else {

				}

			} catch (NumberFormatException e) {
				System.out.println("수자만 입력 가능");
			}
		}

	}

	// 총점구하기
	public int makeSum(int korean, int english, int math) {
		return korean + english + math;
	}

	// 평균구하기
	public int makeAvg(int sum) {
		return sum / 3;
	}

	// 등급구하기
	public String makeGrade(int avg) {
		String grade;
		switch (avg / 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;
	}

	// 성적 범위 체크 (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();
	}
}

1.입력,2.목록,3.상세정보,4.수정,5.삭제,6.종료>2
---------------------------------------
번호	이름	국어	영어	수학	총점	평균	등급
3	완벽	100	100	100	300	100	A	
2	홍길동	88	99	77	264	88	B	
1	가나다	90	80	90	260	86	B	
---------------------------------------
1.입력,2.목록,3.상세정보,4.수정,5.삭제,6.종료>3
선택한 글의 번호:2
번호 : 2
이름 : 홍길동
국어 : 88
영어 : 99
수학 : 77
총점 : 264
평균 : 88
등급 : B
등록일 : 2022-05-25
1.입력,2.목록,3.상세정보,4.수정,5.삭제,6.종료>
profile
한다 열심히

0개의 댓글