Servlet은 웹페이지를 자바를 이용해 동적으로 동작하기 위한 기술이라고 이해하면 된다.


html 문서만 본다면 Servlet 사용전은 사용자 - html 문서의 관계가 되고


Servlet을 적용하면 사용자 - html 문서 - 서버의 java 프로그램이 된다.


예전에 환경할 때 사용했던 Tomcat 버전에 따라 지원하는 Servlet 버전이 다르기 때문에 호환이 되는지 알 필요가 있다.


Tomcat 홈페이지에 가면 알 수 있다.





블로그에서 사용한 톰캣은 8.5.35버전이다.


다음으로는 환경설정이다.


예전 Java Script 설정과 거의 비슷하나 조금 다른부분만 추가로 설명한다. JS 설정 -> https://qdgbjsdnb.tistory.com/162




설정을 쭉 따라하다가 아래와 같은 부분에서 체크박스 체크를 하는 부분이 있다.





이번에는 Java 파일도 사용하므로 Java도 체크한다.


첫번째 예제 Dynamic web Project는 다음과 같이 생성했다.





프로젝트 구성은 다음과 같이 만들었다.






index는 시작페이지


controller는 java 파일이 들어가 Servlet 역할을 할 파일이 된다.


예제의 내용은 처음 페이지에서 링크를 누르면 이클립스의 콘솔창에 첫번째 방문 시 문구가 출력이 되고


반복적으로 새로고침을 하면 출력되는 숫자가 점점 올라간다.







코드는 다음과 같다.


아래에서 사용될 메소드들은 (https://qdgbjsdnb.tistory.com/204?category=727563)에서 정리해놓았다.


index.html



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="/w1/cycle">라이프사이클 테스트하기</a>
</body>
</html>


LifeCycleServlet.java



package controller;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 서블릿을 조금이라도 수정한다면 톰캣을 종료했다가 다시 작동시켜야 한다.

// 아래의 어노테이션을 입력하면 web.xml에 입력했던 연결과 같은 기능을 함.
@WebServlet("/cycle")
public class LifeCycleServlet extends HttpServlet{
	private int initCount = 1;
	private int doGetCount = 1;
	private int destroyCount = 1;
	
	public LifeCycleServlet() {}
	
	public void init(ServletConfig config) throws ServletException {
		System.out.println("init 메소드는 첫 요청시 한 번만 호출됨 : " + initCount++);
	}
	
	public void destroy() {
		System.out.println("destroy 메소드는 톰캣 종료시 호출됨 : " + destroyCount++);
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException{
		System.out.println("doGet 메소드는 요청시마다 호출됨 : " + doGetCount++);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException{
		doGet(request, response);
	}
}



여기서 주목해야 할 점은 Servlet을 수정 즉, java 파일을 수정하면 서버는 껏다 키는걸 권장한다.


두번째는 Servlet api를 사용하는데 오버라이딩 된 init, destroy, doGet 등이 있다.


오버라이드 할 수 있는 함수는 나중에 설명한다.


마지막으로 @WebServlet("/cycle") 부분으로 어노테이션을 통해 Servlet과 HTML 문서 페이지를 연결해주는 키워드이다.


두 가지의 기술을 연결, mapping 시켜주는 키워드이다.


여기서 쓰인 init, destroy, doGet을 설명하면


init은 페이지 호출 시 한번만 실행될 함수


destroy는 톰캣 종료시 실행될 함수


doGet은 새로고침 될 때 올라가는 카운트, 호출 시 계속 실행될 함수이다.




저번에 사용하였던 Statement 구문은 보안에 취약한 방법이다.


SQL Injection이라는 취약점을 가지고 있어 사용하길 권장하지 않는다.


따라서 이 대안으로 PreparedStatement을 사용하면 된다.


PreparedStatement pstmt = null 과 같이 선언하여 사용하고


기존과 같이 선언한 conn을


pstmt = conn.preparedStatement(query문); 과 같이 대입하여 사용한다.


쿼리문을 바로 넣으며


쿼리문은 ? 키워드를 사용하게 된다.


예를들어 SELECT * FROM student WHERE mun = ? AND num = ? 라고 하고 pstmt에 집어넣고


pstmt.set[자료형](?표 순서, 들어갈 값으로 앞의 자료형과 같아야 함);


위와 같은 형식으로 입력한다고 칠 때


pstmt.setString(1, "ABC");

pstmt.setInt(2, 3);


이라고 입력하면 1번 ?에 ABC가 들어가고 2번 ?에 3이라는 값이 들어가


SELECT * FROM student WHERE mun = 'ABC' AND num = 3 이라는 쿼리문이 완성된다.


setString의 경우는 작은 따옴표 '' 키워드는 자동으로 입력된다.





예제를 확인해보자



Employee.java

package model.vo;

import java.sql.Date;

public class Employee implements java.io.Serializable{
	private int empId;
	private String empName;
	private String empNo;
	private String email;
	private String phone;
	private Date hireDate;
	private String jobId;
	private int salary;
	private double bonus;
	private String marriage;
	private int mgrId;
	private String deptId;
	
	public Employee() {}
	
	public Employee(int empId, String empName, String empNo, String email, String phone, Date hireDate, String jobId,
			int salary, double bonus, String marriage, int mgrId, String deptId) {
		super();
		this.empId = empId;
		this.empName = empName;
		this.empNo = empNo;
		this.email = email;
		this.phone = phone;
		this.hireDate = hireDate;
		this.jobId = jobId;
		this.salary = salary;
		this.bonus = bonus;
		this.marriage = marriage;
		this.mgrId = mgrId;
		this.deptId = deptId;
	}

	public Employee(int empId, String empName, String empNo, String email, String phone, String jobId, int salary,
			double bonus, String marriage, int mgrId, String deptId) {
		super();
		this.empId = empId;
		this.empName = empName;
		this.empNo = empNo;
		this.email = email;
		this.phone = phone;
		this.jobId = jobId;
		this.salary = salary;
		this.bonus = bonus;
		this.marriage = marriage;
		this.mgrId = mgrId;
		this.deptId = deptId;
	}

	public Employee(int empId, String jobId, int salary, double bonus, String deptId) {
		super();
		this.empId = empId;
		this.jobId = jobId;
		this.salary = salary;
		this.bonus = bonus;
		this.deptId = deptId;
	}

	public int getEmpId() {
		return empId;
	}

	public void setEmpId(int empId) {
		this.empId = empId;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public String getEmpNo() {
		return empNo;
	}

	public void setEmpNo(String empNo) {
		this.empNo = empNo;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public Date getHireDate() {
		return hireDate;
	}

	public void setHireDate(Date hireDate) {
		this.hireDate = hireDate;
	}

	public String getJobId() {
		return jobId;
	}

	public void setJobId(String jobId) {
		this.jobId = jobId;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

	public double getBonus() {
		return bonus;
	}

	public void setBonus(double bonus) {
		this.bonus = bonus;
	}

	public String getMarriage() {
		return marriage;
	}

	public void setMarriage(String marriage) {
		this.marriage = marriage;
	}

	public int getMgrId() {
		return mgrId;
	}

	public void setMgrId(int mgrId) {
		this.mgrId = mgrId;
	}

	public String getDeptId() {
		return deptId;
	}

	public void setDeptId(String deptId) {
		this.deptId = deptId;
	}
	
	
}



TestMain.java

package controller;

import java.util.Scanner;

import model.dao.EmployeeModel;
import model.vo.Employee;

public class TestJDBC {

	public static void main(String[] args) {
		EmployeeModel model = new EmployeeModel();
		Scanner sc = new Scanner(System.in);
		
		// 모든 직원 조회
		// model.selectAll();
		
		
		
		
		
		
		// 키보드로 사번을 입력받아 사원 조회
		// System.out.print("사번을 입력하세요 : ");
		// model.selectOne(sc.nextInt());
		
		
		
		
		
		/*
		// 새 직원 정보를 키보드로 입력 받아 실행
		// 데이터 입력 시 제약조건 확인해서 잘 넣어야 함
		
		// 키보드 입력하여 변수에 저장
		
		Employee emp = new Employee();
		
		System.out.print("사번을 입력하세요 : ");
		emp.setEmpId(sc.nextInt());
		sc.nextLine();
		System.out.print("이름을 입력하세요 : ");
		emp.setEmpName(sc.nextLine());
		System.out.print("주민번호를 입력하세요 : ");
		emp.setEmpNo(sc.nextLine());
		System.out.print("이메일을 입력하세요 : ");
		emp.setEmail(sc.nextLine());
		System.out.print("전화번호를 입력하세요 : ");
		emp.setPhone(sc.nextLine());
		System.out.print("직급을 입력하세요 : ");
		emp.setJobId(sc.nextLine());
		System.out.print("봉급을 입력하세요 : ");
		emp.setSalary(sc.nextInt());
		sc.nextLine();
		System.out.print("보너스를 입력하세요 : ");
		emp.setBonus(sc.nextDouble());
		sc.nextLine();
		System.out.print("결혼 여부를 입력하세요 : ");
		emp.setMarriage(sc.nextLine());
		System.out.print("사수의 사번을 입력하세요 : ");
		emp.setMgrId(sc.nextInt());
		sc.nextLine();
		System.out.print("Dept ID를 입력하세요 : ");
		emp.setDeptId(sc.nextLine());
		
		model.insertEmployee(emp);
		
		// 사번으로 조회
		model.selectOne(emp.getEmpId());
		
		*/
		
		
		
		
		/*
		// 수정 할 항목의 값을 키보드로 입력 받아 실행
		Employee em = new Employee();
		
		System.out.print("사번을 입력하세요 : ");
		em.setEmpId(sc.nextInt());
		sc.nextLine();
		System.out.print("직급을 입력하세요 : ");
		em.setJobId(sc.nextLine());
		System.out.print("봉급을 입력하세요 : ");
		em.setSalary(sc.nextInt());
		sc.nextLine();
		System.out.print("보너스를 입력하세요 : ");
		em.setBonus(sc.nextDouble());
		sc.nextLine();
		System.out.print("Dept ID를 입력하세요 : ");
		em.setDeptId(sc.nextLine());
		
		// update
		model.updateEmployee(em);
		
		// 사번 입력받아 조회
		model.selectOne(em.getEmpId());
		*/
		
		
		
		
		
		// 키보드로 사번을 입력받아 삭제
		System.out.print("사번을 입력하세요 : ");
		int tempNum = sc.nextInt();
		model.deleteEmployee(tempNum);
		
		// 사번 입력받아 조회
		model.selectOne(tempNum);
		
	}

}



JDBCModel.java

package model.dao;

import java.sql.*;
/*import java.sql.Connection;
import java.sql.ResultSet;*/

import model.vo.Employee;

public class EmployeeModel {
	Connection conn = null;
	Statement stmt = null;
	ResultSet rset = null;
	PreparedStatement pstmt = null;
	String query = "";
	int result = 0;
	
	// 모든 직원 정보 조회용 메소드
	public void selectAll() {
		
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "student", "student");
			
			query = "SELECT * FROM EMPLOYEE";
			
			stmt = conn.createStatement();
			
			rset = stmt.executeQuery(query);
			
			while(rset.next()) {
				System.out.println(rset.getInt("EMP_ID") + ", "
						        + rset.getString("EMP_NAME") + ", "
						        + rset.getString("EMP_NO") + ", "
						        + rset.getString("EMAIL") + ", "
						        + rset.getString("PHONE") + ", "
						        + rset.getDate("HIRE_DATE") + ", "
						        + rset.getString("JOB_ID") + ", "
						        + rset.getInt("SALARY") + ", "
						        + rset.getDouble("BONUS_PCT") + ", "
						        + rset.getString("MARRIAGE") + ", "
						        + rset.getInt("MGR_ID") + ", "
						        + rset.getString("DEPT_ID"));
			}
			
			
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				rset.close();
				stmt.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		
	}
	
	// 사번을 이용해서 직원 한 명의 정보 조회
	public void selectOne(int empId) {

		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "student", "student");
			
			// Statement 사용시
			
			/*String query = "SELECT * FROM EMPLOYEE WHERE EMP_ID = " + empId;
			// Statement는 query만 조작하면 바로 db 공격이 가능하여 보안에 취약
			stmt = conn.createStatement();
			
			rset = stmt.executeQuery(query);*/
			
			// PreparedStatement 사용시
			// PreParedStatement는 위의 보안 이슈를 해결하여 만들어짐
			query = "SELECT * FROM EMPLOYEE WHERE EMP_ID = ?";
			
			pstmt = conn.prepareStatement(query);
			
			pstmt.setInt(1, empId);
			
			rset = pstmt.executeQuery();
			
			if(rset.next()) {
				System.out.println(rset.getInt("EMP_ID") + ", "
				        + rset.getString("EMP_NAME") + ", "
				        + rset.getString("EMP_NO") + ", "
				        + rset.getString("EMAIL") + ", "
				        + rset.getString("PHONE") + ", "
				        + rset.getDate("HIRE_DATE") + ", "
				        + rset.getString("JOB_ID") + ", "
				        + rset.getInt("SALARY") + ", "
				        + rset.getDouble("BONUS_PCT") + ", "
				        + rset.getString("MARRIAGE") + ", "
				        + rset.getInt("MGR_ID") + ", "
				        + rset.getString("DEPT_ID"));
			}
		
		
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				rset.close();
				pstmt.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		
		
	}

	public void insertEmployee(Employee emp) {
		try {
			
			Class.forName("oracle.jdbc.driver.OracleDriver");
			
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "student", "student");
			
			/*
			query = "INSERT INTO employee(emp_Id, emp_Name, emp_No, email, phone, job_Id, salary, bonus_pct, marriage, mgr_Id, dept_Id) " + 
					"VALUES(" + 
					emp.getEmpId() + ", '" +
					emp.getEmpName() + "', '" +
					emp.getEmpNo() + "', '" +
					emp.getEmail() + "', '" +
					emp.getPhone() + "', '" +
					emp.getJobId() + "', " +
					emp.getSalary() + ", " +
					emp.getBonus() + ", '" +
					emp.getMarriage() + "', " +
					emp.getMgrId() + ", " +
					emp.getDeptId() + ")";
			
			stmt = conn.createStatement();
			
			result = stmt.executeUpdate(query);
			*/
			
			query = "INSERT INTO employee(emp_Id, emp_Name, emp_No, email, phone, job_Id, salary, bonus_pct, marriage, mgr_Id, dept_Id) " + 
					"VALUES(" + 
					"?" + ", " +
					"?" + ", " +
					"?" + ", " +
					"?" + ", " +
					"?" + ", " +
					"?" + ", " +
					"?" + ", " +
					"?" + ", " +
					"?" + ", " +
					"?" + ", " +
					"?" + ")";
			
			pstmt = conn.prepareStatement(query);
		
			pstmt.setInt(1, emp.getEmpId());
			pstmt.setString(2, emp.getEmpName());
			pstmt.setString(3, emp.getEmpNo());
			pstmt.setString(4, emp.getEmail());
			pstmt.setString(5, emp.getPhone());
			pstmt.setString(6, emp.getJobId());
			pstmt.setInt(7, emp.getSalary());
			pstmt.setDouble(8, emp.getBonus());
			pstmt.setString(9, emp.getMarriage());
			pstmt.setInt(10, emp.getMgrId());
			pstmt.setString(11, emp.getDeptId());
			
			result = pstmt.executeUpdate();
		
			if(result > 0) {
				System.out.println(result + "개의 행이 추가되었습니다.");
				conn.commit();
			}else {
				System.out.println("실패");
				conn.rollback();
			}
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}

	public void updateEmployee(Employee em) {
try {
			
			Class.forName("oracle.jdbc.driver.OracleDriver");
			
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "student", "student");
			
			
			/*
			stmt = conn.createStatement();		
			
			query = "UPDATE employee SET job_id = '" + em.getJobId() +
					"' WHERE emp_id = " + em.getEmpId();
			System.out.println(query);
			
			
			result = stmt.executeUpdate(query);
			System.out.println(result + "행이 수정되었습니다.");
			
			
			
			query = "UPDATE employee SET salary = " + em.getSalary() +
					" WHERE emp_id = " + em.getEmpId();
			System.out.println(query);
			
			result = stmt.executeUpdate(query);
			System.out.println(result + "행이 수정되었습니다.");
			
			
			
			query = "UPDATE employee SET bonus_pct = " + em.getBonus() +
					" WHERE emp_id = " + em.getEmpId();
			System.out.println(query);
			
			result = stmt.executeUpdate(query);
			System.out.println(result + "행이 수정되었습니다.");
			
			
			
			query = "UPDATE employee SET dept_id = '" + em.getDeptId() +
					"' WHERE emp_id = " + em.getEmpId();
			System.out.println(query);
			
			result = stmt.executeUpdate(query);
			System.out.println(result + "행이 수정되었습니다.");
			*/
			
			
			query = "UPDATE employee SET job_id = ?" +
					"WHERE emp_id = ?";
			System.out.println(query);
			
			pstmt = conn.prepareStatement(query);
			pstmt.setString(1, em.getJobId());
			pstmt.setInt(2, em.getEmpId());
			result = pstmt.executeUpdate();
			System.out.println(result + "행이 수정되었습니다.");
			
			
			
			query = "UPDATE employee SET salary = ?" +
					" WHERE emp_id = ?";
			System.out.println(query);

			pstmt = conn.prepareStatement(query);
			pstmt.setInt(1, em.getSalary());
			pstmt.setInt(2, em.getEmpId());
			result = pstmt.executeUpdate();
			System.out.println(result + "행이 수정되었습니다.");
			
			
			
			query = "UPDATE employee SET bonus_pct = ?" +
					" WHERE emp_id = ?";
			System.out.println(query);

			pstmt = conn.prepareStatement(query);
			pstmt.setDouble(1, em.getBonus());
			pstmt.setInt(2, em.getEmpId());
			result = pstmt.executeUpdate();
			System.out.println(result + "행이 수정되었습니다.");
			
			
			
			query = "UPDATE employee SET dept_id = ?" +
					" WHERE emp_id = ?";
			System.out.println(query);

			pstmt = conn.prepareStatement(query);
			pstmt.setString(1, em.getDeptId());
			pstmt.setInt(2, em.getEmpId());
			result = pstmt.executeUpdate();
			System.out.println(result + "행이 수정되었습니다.");
			
			
			
			conn.commit();
			
			
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void deleteEmployee(int empNo) {
		try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
             
            conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "student", "student");
             
            
            /*
            stmt = conn.createStatement();
             
            query = "DELETE FROM employee WHERE emp_id = " + empNo;
            System.out.println(query);
             
            result = stmt.executeUpdate(query);
             */
            
            query = "DELETE FROM employee WHERE emp_id = ?";
            pstmt = conn.prepareStatement(query);
			pstmt.setInt(1, empNo);
			result = pstmt.executeUpdate();
            
            if (result > 0) {
                System.out.println(result + "개의 행이 수정되었습니다.");
                conn.commit();
            }else {
                System.out.println("실패했습니다.");
                conn.rollback();
            }
             
            
             
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        } catch (SQLException e1) {
            e1.printStackTrace();
        } finally {
            try {
                pstmt.close();
                conn.close();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
	}

}








저번 프로젝트 파일에 이어서


설명(주석)과 함께 예제를 올립니다.






employee는 생성자가 약간 수정되었다.


package model.vo;

import java.sql.Date;

// 보통 vo 클래스 파일의 이름을 DB의 이름과 같게한다.

// vo(value object) == entity == record == row
// do(domain object) == dto(data transfer object)
// DB 테이블의 한 행의 정보가 기록되는 저장용 객체

// 1. 반드시 캡슐화가 적용되어야 한다 : 모든 필드는 private가 된다.
// 2. 기본 생성자와 매개변수 있는 생성자를 작성해야 한다. (매개변수가 있는 생성자가 있다면 기본 생성자를 jvm에서 생성해주지 않기 때문)
// 3. 모든 필드에 대해 getter와 setter 작성해야 한다.
// 4. 직렬화 처리를 해야 한다.
// optional. toString() 오버라이딩 <- 필드값을 확인하기 위해

public class Employee implements java.io.Serializable{
	private int empNo;
	private String empName;
	private String job;
	private int mgr;
	private Date hireDate;
	private int sal;
	private int comm;
	private int deptNo;
	// 이러한 객체를 vo 객체라고 할 수 있다.
	
	public Employee() {
		
	}
	
	public Employee(int empNo, String empName, String job, int mgr, Date hireDate, int sal, int comm, int deptNo) {
		super();
		this.empNo = empNo;
		this.empName = empName;
		this.job = job;
		this.mgr = mgr;
		this.hireDate = hireDate;
		this.sal = sal;
		this.comm = comm;
		this.deptNo = deptNo;
	}
	
	public Employee(int empNo, String empName, String job, int mgr, int sal, int comm, int deptNo) {
		super();
		this.empNo = empNo;
		this.empName = empName;
		this.job = job;
		this.mgr = mgr;
		this.sal = sal;
		this.comm = comm;
		this.deptNo = deptNo;
	}
	
	public Employee(int empNo, String job, int sal, int comm) {
		super();
		this.empNo = empNo;
		this.job = job;
		this.sal = sal;
		this.comm = comm;
	}

	public int getEmpNo() {
		return empNo;
	}

	public void setEmpNo(int empNo) {
		this.empNo = empNo;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public String getJob() {
		return job;
	}

	public void setJob(String job) {
		this.job = job;
	}

	public int getMgr() {
		return mgr;
	}

	public void setMgr(int mgr) {
		this.mgr = mgr;
	}

	public Date getHireDate() {
		return hireDate;
	}

	public void setHireDate(Date hireDate) {
		this.hireDate = hireDate;
	}

	public int getSal() {
		return sal;
	}

	public void setSal(int sal) {
		this.sal = sal;
	}

	public int getComm() {
		return comm;
	}

	public void setComm(int comm) {
		this.comm = comm;
	}

	public int getDeptNo() {
		return deptNo;
	}

	public void setDeptNo(int deptNo) {
		this.deptNo = deptNo;
	}
	
	
	
	
}


testMain은 주석을 지워가며 한개 씩 테스트 해보세요.


package controller;

import model.dao.JDBCModel;
import model.vo.Employee;

public class TestMain {

	public static void main(String[] args) {
		JDBCModel model = new JDBCModel();
		
		// 전체 조회
		// model.testJDBC();
		
		
		
		// 사번 전달하여 조회
		// model.testJDBC2(7839);
		
		
		
		// 객체 생성 후 삽입
		// Employee emp = new Employee(7777, "JARON", "ANALYST", 9999, 12000, 90, 10);
		// model.testInsert(emp);
		
		
		
		// 객체 생성 후 업데이트
		// Employee e = new Employee(7777, "CHAIRMAN", 50000000, 100000000);
		// model.testUpdate(e);
		// 업데이트 후 전체 조회
		// model.testJDBC();
		
		
		
		// 사번 전달 후 삭제
		// model.testDelete(7777);
		// 삭제 후 전체 조회
		// model.testJDBC();
	}

}





JDBC 모델은 메인에서 호출한 다양한 기능들을 작성하였다.



package model.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import model.vo.Employee;

public class JDBCModel {
	// 사원 전체 조회용 메소드
	public void testJDBC() {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rset = null;
		// ctrl + shift + O 를 누르면 import 해야하는 항목이 나옴.
		
		// 1. 해당 데이터 베이스에 대한 라이브러리 등록 작업
		// Class.forName("클래스명"); // ClassNotFoundException 처리를 해야 함
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			
			// 2.데이터베이스와 연결함  // SQLException 처리를 해야한다.
			conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:xe", "scott", "tiger");
			
			System.out.println(conn);
			
			// 3. 쿼리문 작성 후 DB에서 쿼리문 실행시키고 결과를 가지고 옴
			String query = "SELECT * FROM EMP";
			
			stmt = conn.createStatement();
			
			rset = stmt.executeQuery(query);
			
			while (rset.next()) {
				System.out.println(rset.getInt("EMPNO") + ", " + 
									rset.getString("ENAME") + ", " +
									rset.getString("JOB") + ", " +
									rset.getInt("MGR") + ", " +
									rset.getDate("HIREDATE") + ", " + 
									rset.getInt("SAL") + ", " +
									rset.getInt("COMM") + ", " +
									rset.getInt("DEPTNO")
						);
				
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				// 4. DB와 관련된 객체는 반드시 close 해야 함
				rset.close();
				stmt.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}

	public void testJDBC2(int empNo) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rset = null;
		
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			
			conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:xe", "scott", "tiger");
			
			String query = "SELECT * FROM EMP WHERE EMPNO = " + empNo;
			
			stmt = conn.createStatement();
			
			rset = stmt.executeQuery(query);
			
			while (rset.next()) {
				System.out.println(rset.getInt("EMPNO") + ", " + 
						rset.getString("ENAME") + ", " +
						rset.getString("JOB") + ", " +
						rset.getInt("MGR") + ", " +
						rset.getDate("HIREDATE") + ", " + 
						rset.getInt("SAL") + ", " +
						rset.getInt("COMM") + ", " +
						rset.getInt("DEPTNO")
					);
				
			}
			

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				rset.close();
				stmt.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}

	public void testInsert(Employee emp) {
		Connection conn = null;
		Statement stmt = null;
		int result = 0;
		
		// 문자열의 경우 ''을 추가해야 함을 주의하자
		String query = "INSERT INTO EMP(EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)"
				+ "VALUES(" +
				emp.getEmpNo() + ", '" + 
				emp.getEmpName() + "', '" + 
				emp.getJob() + "', " + 
				emp.getMgr() + ", " + 
				"SYSDATE, " +
				emp.getSal() + ", " + 
				emp.getComm() + ", " +
				emp.getDeptNo() +
				")";
		System.out.println(query);
		
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "scott", "tiger");
			
			stmt = conn.createStatement();
			
			result = stmt.executeUpdate(query);
			
			if(result > 0) {
				// DB와 마찬가지로 commit rollback을 상황에 맞게 해야한다.
				System.out.println(result + "개의 행이 추가되었습니다.");
				conn.commit();
			}else {
				System.out.println(result + "개의 행 추가 실패!");
				conn.rollback();
			}
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				stmt.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}

	public void testUpdate(Employee e) {
		Connection conn = null;
		Statement stmt = null;
		int result = 0;
		
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "scott", "tiger");
			
			stmt = conn.createStatement();
			
			String query = "UPDATE emp SET " +
					"JOB = '" + e.getJob() + 
					"' WHERE empNo = " +
					e.getEmpNo();
			System.out.println(query);
			
			result = stmt.executeUpdate(query);
			
			System.out.println(result + "개의 행이 수정되었습니다.");
			
			
			
			query = "UPDATE emp SET " +
					"SAL = " + e.getSal() + 
					" WHERE empNo = " +
					e.getEmpNo();
			System.out.println(query);
			
			result = stmt.executeUpdate(query);
			
			System.out.println(result + "개의 행이 수정되었습니다.");
			
			
			
			query = "UPDATE emp SET " +
					"COMM = " + e.getComm() + 
					" WHERE empNo = " +
					e.getEmpNo();
			System.out.println(query);
			
			result = stmt.executeUpdate(query);
			
			System.out.println(result + "개의 행이 수정되었습니다.");
			
			conn.commit();
			
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		} catch (SQLException e1) {
			e1.printStackTrace();
		} finally {
			try {
				stmt.close();
				conn.close();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
	}

	public void testDelete(int empNo) {
		Connection conn = null;
		Statement stmt = null;
		int result = 0;
		
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "scott", "tiger");
			
			stmt = conn.createStatement();
			
			String query = "DELETE FROM emp WHERE empNo = " + empNo; 
			System.out.println(query);
			
			result = stmt.executeUpdate(query);
			
			if (result > 0) {
				System.out.println(result + "개의 행이 수정되었습니다.");
			}else {
				System.out.println("실패했습니다.");
			}
			
			conn.commit();
			
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		} catch (SQLException e1) {
			e1.printStackTrace();
		} finally {
			try {
				stmt.close();
				conn.close();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
	}
}


+ Recent posts