JDBC 입력 업데이트 삭제

JDBC 템플릿을 이용하면 드라이버 설정이나 기타 설정을 안하여도 된다.

/*  Statement 란?
            SQL 문을 저장하고 실행한 뒤 결과를 받아 주는
            매소드들이 묶여있는 타입의 클래스
    */
    
Connection con = getConnection();
        //쿼리문을 저장하고 실행하는 기능을 하는 용도의 인터페이스
        Statement stmt = null;
        //select 조회의 결과 집합을 받아 올 용도의 인터페이스
        ResultSet rset = null;        
     try {
            // connection 을 이용해서 statement 인스턴스 생성
            stmt = con.createStatement();
            // executeQuery() 메소드를 호출해서 SQL 문을 수행(SQL 문을 String 형태로 전달)
            rset = stmt.executeQuery("SELECT emp_id, emp_name FROM employee");
            while(rset.next()){
                /* next() : ResultSet 의 커서 위치를 하나씩 내리면서 행이 존재하면 true */
                System.out.println(rset.getString("emp_id") + " , " + rset.getString("emp_name"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            close(con);
            close(stmt);
            close(rset);
        }

JDBC 템플릿을 이용하면 드라이버 설정이나 기타 설정을 안하여도 된다.

import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBCTemplate {

    public static Connection getConnection() {

        Connection con = null;

        Properties prop = new Properties();

        try {
            prop.load(new FileReader("파일 경로"));

            String driver = prop.getProperty("driver");
            String url = prop.getProperty("url");

            Class.forName(driver);
            con = DriverManager.getConnection(url,prop);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return con;
    }


    public static void close(Connection con) {

        try {
            if( con != null && !con.isClosed()){
                con.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void close(Statement stmt) {

        try {
            if( stmt != null && !stmt.isClosed()){
                stmt.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void close(ResultSet rset) {
        try {
            if( rset != null && !rset.isClosed()){
                rset.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


}
설정 파일

driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost/employee
user = ohgiraffers
password = ohgiraffers

DTO 클래스

데이터를 한곳에 모아서 관리한다.

/*
        DTO (Data Transfer Object)
        여러 계층 (Class) 간의 데이터 전송을 ㅜ이해 다양한 타입의 데이터를
        하나로 묶어 전송하는 쓰임의 클래스
        유사한 말로 VO, Bean, Entity, (DO, Domain, Row) 등등 많이 불리운다.
     */
    /* 
        DTO 클래스의 조건
        1. 모든 필드는 private
        2. 기본 생성자와 모든 필드를 초기화 하는 생성자
        3. 모든 필드에 대한 getter / setter
        4. toString Overriding 을 이용한 필드 값 반환용 메소드
     */

import java.sql.Date;

public class EmployeeDTO {

    private String empId;
    private String empName;
    private String empNo;
    private String email;
    private String phone;
    private String deptCode;
    private String jobCode;
    private String salLevel;
    private int salary;
    private double bonus;
    private String managerId;
    private Date hireDate;
    private Date entDate;
    private String entYN;


    public EmployeeDTO() {
    }

    public EmployeeDTO(String empId, String empName, String empNo, String email, String phone, String deptCode, String jobCode, String salLevel, int salary, double bonus, String managerId, Date hireDate, Date entDate, String entYN) {
        this.empId = empId;
        this.empName = empName;
        this.empNo = empNo;
        this.email = email;
        this.phone = phone;
        this.deptCode = deptCode;
        this.jobCode = jobCode;
        this.salLevel = salLevel;
        this.salary = salary;
        this.bonus = bonus;
        this.managerId = managerId;
        this.hireDate = hireDate;
        this.entDate = entDate;
        this.entYN = entYN;
    }

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String 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 String getDeptCode() {
        return deptCode;
    }

    public void setDeptCode(String deptCode) {
        this.deptCode = deptCode;
    }

    public String getJobCode() {
        return jobCode;
    }

    public void setJobCode(String jobCode) {
        this.jobCode = jobCode;
    }

    public String getSalLevel() {
        return salLevel;
    }

    public void setSalLevel(String salLevel) {
        this.salLevel = salLevel;
    }

    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 getManagerId() {
        return managerId;
    }

    public void setManagerId(String managerId) {
        this.managerId = managerId;
    }

    public Date getHireDate() {
        return hireDate;
    }

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

    public Date getEntDate() {
        return entDate;
    }

    public void setEntDate(Date entDate) {
        this.entDate = entDate;
    }

    public String getEntYN() {
        return entYN;
    }

    public void setEntYN(String entYN) {
        this.entYN = entYN;
    }

    @Override
    public String toString() {
        return "EmployeeDTO{" +
                "empId='" + empId + '\'' +
                ", empName='" + empName + '\'' +
                ", empNo='" + empNo + '\'' +
                ", email='" + email + '\'' +
                ", phone='" + phone + '\'' +
                ", deptCode='" + deptCode + '\'' +
                ", jobCode='" + jobCode + '\'' +
                ", salLevel='" + salLevel + '\'' +
                ", salary=" + salary +
                ", bonus=" + bonus +
                ", managerId='" + managerId + '\'' +
                ", hireDate=" + hireDate +
                ", entDate=" + entDate +
                ", entYN='" + entYN + '\'' +
                '}';
    }
}

ALT + INS 하면 자동으로 만들어준다.

DB 입력 업데이트 삭제

전부 비슷하고 쿼리문만 바뀜

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

import static com.ohgiraffers.common.JDBCTemplate.close;
import static com.ohgiraffers.common.JDBCTemplate.getConnection;

public class Application01 {

    public static void main(String[] args) {

        Connection con = getConnection();

        PreparedStatement pstmt = null;

        int result = 0;

        Properties prop = new Properties();

        try {
            prop.loadFromXML(new FileInputStream("쿼리정보"));
            String query = prop.getProperty("insertMenu");
            System.out.println("query = " + query);

            pstmt = con.prepareStatement(query);

            pstmt.setString(1,"봉골레청국장");
            pstmt.setInt(2,50000);
            pstmt.setInt(3,1);
            pstmt.setString(4,"Y");

            result = pstmt.executeUpdate();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            close(con);
            close(pstmt);
        }
        System.out.println("result = " + result);
    }
}