JDBC - DAY 4

NewTypeAsuka·2023년 3월 22일
0

JDBC@

목록 보기
5/10

오늘도 역시 하루종일 코드만 두드렸다.

그래서 딱히 메모할 것은 없지만 오늘 두드린 코드 일부를 간단하게 올려본다.

모두 깔끔하게 정리된 코드다.

다른 이야기지만 나는 코드를 깔끔하게 정리하는 걸 매우 좋아하는 것 같다!

성격 어디 가나..

package edu.kh.jdbc.view;

import java.sql.SQLException;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;

import edu.kh.jdbc.model.dto.Emp;
import edu.kh.jdbc.model.service.EmpService;

public class EmpView {
  
	private Scanner sc = new Scanner(System.in);
	
	private EmpService service = new EmpService();
	
	public void displayMenu() {
		
		int input = 0;
		
		do {
			
			try {
				System.out.println("\n*****************************\n");
				System.out.println("***** 사원 관리 프로그램*****");
				
				System.out.println("1. 재직 중인 사원 전체 조회"); 
				
				System.out.println("2. 퇴직한 사원 전체 조회"); 
				
				System.out.println("3. 사번이 일치하는 사원 조회"); 
				
				System.out.println("4. 사원 정보 추가(INSERT)");
				
				System.out.println("5. 사번으로 사원 정보 수정(UPDATE)");
				
				System.out.println("6. 사번으로 사원 정보 삭제(DELETE)");
				
				System.out.println("7. 사번이 일치하는 사원 퇴직 처리");
                
				System.out.println("8. 가장 최근 입사한 사원 5명 조회");
				
				System.out.println("9. 부서별 통계 조회"); 
				
				System.out.println("0. 프로그램 종료");
				
				System.out.print("메뉴 선택 >> ");
				input = sc.nextInt();
				sc.nextLine();
				
				switch(input) {
				case 1: selectAll(); break;
				case 2: selectRetiredAll(); break;
				case 3: selectOne(); break;
				case 4: insertEmployee(); break;
				case 5: updateEmployee(); break;
				case 6: deleteEmployee(); break;
				case 7: retireEmployee(); break;
				case 8: selectNewFive(); break;
				case 9: selectDept(); break;
				case 0: System.out.println("\n[프로그램을 종료합니다.]\n"); break;
				
				default: System.out.println("\n[메뉴에 존재하는 번호를 입력하세요.]\n");
				}
			}catch (InputMismatchException e) {
				System.out.println("\n[잘못된 입력입니다.]\n");
				sc.nextLine();
				input = -1;
			}
		}while(input != 0);
	}
	
	/**
	 * 1. 재직 중인 사원 전체 조회
	 */
	private void selectAll() {
		System.out.println("\n----- 재직 중인 사원 전체 조회 -----\n");
		
		try {
			List<Emp> empList = service.selectAll();
			
			if(empList.isEmpty()) {
				System.out.println("\n[조회된 사원이 없습니다.]\n");
				return;
			}
			
			for(Emp emp : empList) {
				System.out.printf("%d / %s / %s / %s / %s / %s \n", 
						emp.getEmpId(), 
						emp.getEmpName(),
						emp.getDepartmentTitle(),
						emp.getJobName(),
						emp.getPhone(),
						emp.getEmail());
			}
		} catch(SQLException e) {
			System.out.println("\n[재직 중인 사원 전체 조회 중 예외 발생]\n");
			e.printStackTrace();
		}
	}
	
	/**
	 * 2. 퇴직한 사원 전체 조회
	 */
	private void selectRetiredAll() {
		System.out.println("\n----- 퇴직한 사원 전체 조회 -----\n");
		
		try {
			List<Emp> empList = service.selectRetiredAll();
			
			if(empList.isEmpty()) {
				System.out.println("\n[퇴직한 사원이 없습니다.]\n");
				return;
			}
			
			for(Emp emp : empList) {
				System.out.printf("%d / %s / %s / %s / %s \n",
						emp.getEmpId(),
						emp.getEmpName(),
						emp.getPhone(),
						emp.getEmail(),
						emp.getEntDate());
			}
		} catch(SQLException e) {
			System.out.println("\n[퇴직한 사원 전체 조회 중 예외 발생]\n");
			e.printStackTrace();
		}
	}
	
	/**
	 * 3. 사번이 일치하는 사원 조회
	 */
	private void selectOne() {
		System.out.println("\n----- 사번이 일치하는 사원 조회 -----\n");

		System.out.print("사번 입력: ");
		int input = sc.nextInt();
		sc.nextLine();
		
		try {
			Emp emp = service.selectOne(input);
			
			if(emp == null) {
				System.out.println("\n[사번이 일치하는 사원이 없습니다.]\n");
				return;
			}
			
			System.out.printf("%s / %s / %s / %s / %d / %s / %s / %s / %s", 
					emp.getEmpId(),
					emp.getEmpName(),
					emp.getDepartmentTitle(),
					emp.getJobName(),
					emp.getSalary(),
					emp.getPhone(),
					emp.getEmail(),
					emp.getHireDate(),
					emp.getEntYN());
		} catch(SQLException e) {
			System.out.println("\\n[사번이 일치하는 사원 조회 중 예외 발생]\\n");
			e.printStackTrace();
		}
	}
	
	/**
	 * 4. 사원 정보 추가(INSERT)
	 */
	private void insertEmployee() {
		System.out.println("\n----- 사원 정보 추가 -----\n");

		System.out.print("사원명 입력: ");
		String inputEmpName = sc.next();
		System.out.print("주민등록번호 입력(- 포함): ");
		String inputEmpNo = sc.next();
		System.out.print("이메일 입력: ");
		String inputEmail = sc.next();
		System.out.print("전화번호 입력(- 생략): ");
		String inputPhone = sc.next();
		System.out.print("부서코드 입력(D1 ~ D9): ");
		String inputDeptCode = sc.next();
		System.out.print("직급코드 입력(J1 ~ J7): ");
		String inputJobCode = sc.next();
		System.out.print("급여등급 입력(S1 ~ S6): ");
		String inputSalLevel = sc.next();
		System.out.print("급여 입력: ");
		int inputSalary = sc.nextInt();
		System.out.print("보너스 입력: ");
		double inputBonus = sc.nextDouble();
		System.out.print("관리자사번 입력: ");
		int inputManagerId = sc.nextInt();
		sc.nextLine();
		
		Emp emp = new Emp(inputEmpName, inputEmpNo, inputEmail, inputPhone, inputDeptCode, 
				inputJobCode, inputSalLevel, inputSalary, inputBonus, inputManagerId);
		
		try {
			int result = service.insertEmployee(emp);
			
			if(result > 0) System.out.println("[삽입 성공]");
			else System.out.println("[삽입 실패]");
		} catch(SQLException e) {
			System.out.println("\n[사원 정보 추가 중 예외 발생]\n");
			e.printStackTrace();
		}
	}
	
	/**
	 * 5. 사번으로 사원 정보 수정(UPDATE)
	 */
	private void updateEmployee() {
		System.out.println("\n----- 사번으로 사원 정보 수정 -----\n");
		
		System.out.print("정보를 수정할 사번 입력: ");
		int inputEmpId = sc.nextInt();
		System.out.print("수정할 이메일 입력: ");
		String inputEmail = sc.next();
		System.out.print("수정할 전화번호 입력(- 생략): ");
		String inputPhone = sc.next();
		System.out.print("수정할 급여 입력: ");
		int inputSalary = sc.nextInt();
		System.out.print("수정할 보너스 입력: ");
		double inputBonus = sc.nextDouble();
		sc.nextLine();
		
	    Emp emp = new Emp();
	    emp.setEmpId(inputEmpId);
	    emp.setEmail(inputEmail);
	    emp.setPhone(inputPhone);
	    emp.setSalary(inputSalary);
	    emp.setBonus(inputBonus);
		
		try {
			int result = service.updateEmployee(emp);
			if(result > 0) System.out.println("[수정 성공]");
			else System.out.println("[사번이 일치하는 사원이 없습니다.]");
		} catch(SQLException e) {
			System.out.println("\n[사원 정보 수정 중 예외 발생]\n");
			e.printStackTrace();
		}
	}
	
	/**
	 * 6. 사번으로 사원 정보 삭제(DELETE)
	 */
	private void deleteEmployee() {
		System.out.println("\n----- 사번으로 사원 정보 삭제 -----\n");
		
		System.out.print("삭제할 사원의 사번 입력: ");
		int input = sc.nextInt();
		System.out.print("정말로 삭제하시겠습니까? (Y/N)");
		char check = sc.next().toUpperCase().charAt(0);
	    if(check == 'N') {
	    	System.out.println("[취소되었습니다.]");
	    	return;
	    }
	    if(check != 'Y') {
	    	System.out.println("[Y 또는 N을 입력해주세요.]");
	    	return;
	    }
		sc.nextLine();
		
		Emp emp = new Emp();
		emp.setEmpId(input);
		
		try {
			int result = service.deleteEmployee(input);
			if(result > 0) System.out.println("[삭제 성공]");
			else System.out.println("[사번이 일치하는 사원이 없습니다.]");
		} catch(SQLException e) {
			System.out.println("\n[사원 정보 삭제 중 예외 발생]\n");
			e.printStackTrace();
		}
	}
	
	/**
	 * 7. 사번이 일치하는 사원 퇴직 처리
	 */
	private void retireEmployee() {
		System.out.println("\n----- 사번이 일치하는 사원 퇴직 처리 -----\n");

		System.out.print("퇴직 처리할 사원의 사번 입력: ");
		int input = sc.nextInt();
		System.out.print("정말로 퇴직 처리하시겠습니까? (Y/N)");
		char check = sc.next().toUpperCase().charAt(0);
	    if(check == 'N') {
	    	System.out.println("[취소되었습니다.]");
	    	return;
	    }
	    if(check != 'Y') {
	    	System.out.println("[Y 또는 N을 입력해주세요.]");
	    	return;
	    }
		sc.nextLine();
		
		Emp emp = new Emp();
		emp.setEmpId(input);
		
		try {
			int result = service.retireEmployee(input);
			if(result > 0) System.out.println("[퇴직 처리 성공]");
			else System.out.println("[사번이 일치하는 않거나, 이미 퇴직된 사원입니다.]");
		} catch(SQLException e) {
			System.out.println("\n[사원 퇴직 처리 중 예외 발생]\n");
			e.printStackTrace();
		}
	}
	
	/**
	 * 8. 가장 최근 입사한 사원 5명 조회
	 */
	private void selectNewFive() {
		System.out.println("\n----- 가장 최근 입사한 사원 5명 조회 -----\n");

	}
	
	/**
	 * 9. 부서별 통계 조회
	 */
	private void selectDept() {
		System.out.println("\n----- 부서별 통계 조회 -----\n");

	}
}
package edu.kh.jdbc.model.service;

import static edu.kh.jdbc.common.JDBCTemplate.*;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import edu.kh.jdbc.model.dao.EmpDAO;
import edu.kh.jdbc.model.dto.Emp;

public class EmpService {

	private EmpDAO dao = new EmpDAO();

	/**
	 * 1. 재직 중인 사원 전체 조회 서비스
	 * @return empList
	 * @throws SQLException
	 */
	public List<Emp> selectAll() throws SQLException {
		
		Connection conn = getConnection();
		List<Emp> empList = dao.selectAll(conn);
		close(conn);
		
		return empList;
	}

	/**
	 * 2. 퇴직한 사원 전체 조회 서비스
	 * @return empList
	 * @throws SQLException
	 */
	public List<Emp> selectRetiredAll() throws SQLException {

		Connection conn = getConnection();
		List<Emp> empList = dao.selectRetiredAll(conn);
		close(conn);
		
		return empList;
	}


	/**
	 * 3. 사번이 일치하는 사원 조회 서비스
	 * @param input
	 * @return emp
	 * @throws SQLException
	 */
	public Emp selectOne(int input) throws SQLException {
		
		Connection conn = getConnection();
		Emp emp = dao.selectOne(conn, input);
		close(conn);
		
		return emp;
	}

	/**
	 * 4. 사원 정보 추가 서비스
	 * @param emp
	 * @return result
	 * @throws SQLException
	 */
	public int insertEmployee(Emp emp) throws SQLException {
		
		Connection conn = getConnection();
		int result = dao.insertEmployee(conn, emp);
		if(result > 0) commit(conn);
		else rollback(conn);
		close(conn);
		
		return result;
	}

	/**
	 * 5. 사원 정보 수정 서비스
	 * @param emp
	 * @return result
	 * @throws SQLException
	 */
	public int updateEmployee(Emp emp) throws SQLException {
		
		Connection conn = getConnection();
		int result = dao.updateEmployee(conn, emp);
		if(result > 0) commit(conn);
		else rollback(conn);
		close(conn);
		
		return result;
	}

	/**
	 * 6. 사원 정보 삭제 서비스
	 * @param input
	 * @return result
	 * @throws SQLException
	 */
	public int deleteEmployee(int input) throws SQLException {
		
		Connection conn = getConnection();
		int result = dao.deleteEmployee(conn, input);
		if(result > 0) commit(conn);
		else rollback(conn);
		close(conn);
		
		return result;
	}

	/**
	 * 7. 사번이 일치하는 사원 퇴직 처리 서비스
	 * @param input
	 * @return result
	 * @throws SQLException
	 */
	public int retireEmployee(int input) throws SQLException {
		
		Connection conn = getConnection();
		int result = dao.retireEmployee(conn, input);
		if(result > 0) commit(conn);
		else rollback(conn);
		close(conn);
		
		return result;
	}
}
package edu.kh.jdbc.model.dao;

import static edu.kh.jdbc.common.JDBCTemplate.*;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.util.ArrayList;
import java.util.List;

import edu.kh.jdbc.model.dto.Emp;

public class EmpDAO {

	private Statement stmt;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	/**
	 * 1. 재직 중인 사원 전체 조회 결과 반환 메서드
	 * @param conn
	 * @return empList
	 * @throws SQLException
	 */
	public List<Emp> selectAll(Connection conn) throws SQLException {
		
		List<Emp> empList = new ArrayList<>();
		
		try {
			String sql = "SELECT EMP_ID, EMP_NAME, DEPT_TITLE, JOB_NAME, PHONE, EMAIL\r\n"
					+ "FROM EMPLOYEE\r\n"
					+ "LEFT JOIN DEPARTMENT ON (DEPT_CODE = DEPT_ID)\r\n"
					+ "LEFT JOIN JOB USING (JOB_CODE)\r\n"
					+ "WHERE ENT_YN = 'N'\r\n"
					+ "ORDER BY JOB_CODE ASC";
			
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			
			while(rs.next()) {
				String empId = rs.getString(1);
				String empName = rs.getString(2);
				String departmentTitle = rs.getString(3);
				String jobName = rs.getString(4);
				String phone = rs.getString(5);
				String email = rs.getString(6);
				
				Emp emp = new Emp();
				emp.setEmpId(Integer.parseInt(empId));
				emp.setEmpName(empName);
				emp.setDepartmentTitle(departmentTitle);
				emp.setJobName(jobName);
				emp.setPhone(phone);
				emp.setEmail(email);
				
				empList.add(emp);
			}
		} finally {
			close(rs);
			close(stmt);
		}
		return empList;
	}

	/**
	 * 2. 퇴직한 사원 전체 조회 결과 반환 메서드
	 * @param conn
	 * @return empList
	 * @throws SQLException
	 */
	public List<Emp> selectRetiredAll(Connection conn) throws SQLException {

		List<Emp> empList = new ArrayList<>();
		
		try {
			String sql = "SELECT EMP_ID, EMP_NAME, PHONE, EMAIL, ENT_DATE\r\n"
					+ "FROM EMPLOYEE\r\n"
					+ "WHERE ENT_YN = 'Y'\r\n"
					+ "ORDER BY ENT_DATE ASC";
			
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			
			while(rs.next()) {
				String empId = rs.getString(1);
				String empName = rs.getString(2);
				String phone = rs.getString(3);
				String email = rs.getString(4);
				String entDate = rs.getString(5);
				
				Emp emp = new Emp();
				emp.setEmpId(Integer.parseInt(empId));
				emp.setEmpName(empName);
				emp.setPhone(phone);
				emp.setEmail(email);
				emp.setEntDate(entDate);
				
				empList.add(emp);
			}
		} finally {
			close(rs);
			close(stmt);
		}
		return empList;
	}

	/**
	 * 3. 사번이 일치하는 사원 조회 결과 반환 메서드
	 * @param conn
	 * @param input
	 * @return emp
	 * @throws SQLException
	 */
	public Emp selectOne(Connection conn, int input) throws SQLException {
		
		Emp emp = null;
		
		try {
			String sql = "SELECT EMP_ID, EMP_NAME, DEPT_TITLE, JOB_NAME, SALARY, PHONE, EMAIL, HIRE_DATE, ENT_YN\r\n"
					+ "FROM EMPLOYEE\r\n"
					+ "LEFT JOIN DEPARTMENT ON (DEPT_CODE = DEPT_ID)\r\n"
					+ "LEFT JOIN JOB USING (JOB_CODE)\r\n"
					+ "WHERE EMP_ID = ?";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, input);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				String empId = rs.getString(1);
				String empName = rs.getString(2);
				String departmentTitle = rs.getString(3);
				String jobName = rs.getString(4);
				int salary = rs.getInt(5);
				String phone = rs.getString(6);
				String email = rs.getString(7);
				Date hireDate = rs.getDate(8);
				String entYN = rs.getString(9);
				
				emp = new Emp();
				emp.setEmpId(Integer.parseInt(empId));
				emp.setEmpName(empName);
				emp.setDepartmentTitle(departmentTitle);
				emp.setJobName(jobName);
				emp.setSalary(salary);
				emp.setPhone(phone);
				emp.setEmail(email);
				emp.setHireDate(hireDate);
				emp.setEntYN(entYN);
			}
		} finally {
			close(rs);
			close(stmt);
		}
		return emp;
	}

	/**
	 * 4. 사원 정보 추가 결과 반환 메서드
	 * @param conn
	 * @param emp
	 * @return result
	 * @throws SQLException
	 */
	public int insertEmployee(Connection conn, Emp emp) throws SQLException {
		
		int result = 0;
		
		try {
			String sql = "INSERT INTO EMPLOYEE\r\n"
					+ "VALUES (SEQ_EMP_ID.NEXTVAL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, SYSDATE, NULL, 'N')";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, emp.getEmpName());
			pstmt.setString(2, emp.getEmpNo());
			pstmt.setString(3, emp.getEmail());
			pstmt.setString(4, emp.getPhone());
			pstmt.setString(5, emp.getDeptCode());
			pstmt.setString(6, emp.getJobCode());
			pstmt.setString(7, emp.getSalLevel());
			pstmt.setInt(8, emp.getSalary());
			pstmt.setDouble(9, emp.getBonus());
			pstmt.setInt(10, emp.getManagerId());
			result = pstmt.executeUpdate();
		} finally {
			close(pstmt);
		}
		return result;
	}

	/**
	 * 5. 사원 정보 수정 결과 반환 메서드
	 * @param conn
	 * @param emp
	 * @return result
	 * @throws SQLException
	 */
	public int updateEmployee(Connection conn, Emp emp) throws SQLException {
		
		int result = 0;
		
		try {
			String sql = "UPDATE EMPLOYEE\r\n"
					+ "SET EMAIL = ?,\r\n"
					+ "PHONE = ?,\r\n"
					+ "SALARY = ?,\r\n"
					+ "BONUS = ?\r\n"
					+ "WHERE EMP_ID = ?";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, emp.getEmail());
			pstmt.setString(2, emp.getPhone());
			pstmt.setInt(3, emp.getSalary());
			pstmt.setDouble(4, emp.getBonus());
			pstmt.setInt(5, emp.getEmpId());
			result = pstmt.executeUpdate();
		} finally {
			close(pstmt);
		}
		return result;
	}

	/**
	 * 6. 사원 정보 삭제 결과 반환 메서드
	 * @param conn
	 * @param input
	 * @return result
	 * @throws SQLException
	 */
	public int deleteEmployee(Connection conn, int input) throws SQLException {
		
		int result = 0;
		
		try {
			String sql = "DELETE FROM EMPLOYEE\r\n"
					+ "WHERE EMP_ID = " + input;
			
			stmt = conn.createStatement();
			result = stmt.executeUpdate(sql);
		} finally {
			close(stmt);
		}
		return result;
	}

	/**
	 * 7. 사번이 일치하는 사원 퇴직 처리 결과 반환 메서드
	 * @param conn
	 * @param input
	 * @return result
	 * @throws SQLException
	 */
	public int retireEmployee(Connection conn, int input) throws SQLException {
		
		int result = 0;
		
		try {
			String sql = "UPDATE EMPLOYEE\r\n"
					+ "SET ENT_YN = 'Y', ENT_DATE = SYSDATE\r\n"
					+ "WHERE EMP_ID = " + input;
			
			stmt = conn.createStatement();
			result = stmt.executeUpdate(sql);
		} finally {
			close(stmt);
		}
		return result;
	}
}
profile
언제나 노력하는 개발자입니다.

0개의 댓글