Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

정리정돈 개발블로그~

[36일차] 국비 교육 본문

국비학원 교육 일지

[36일차] 국비 교육

snooop 2022. 9. 7. 17:49

<JDBC>

:자바에서 데이터베이스에 접속할 수 있도록 하는 자바 API이다.

데이터베이스에서 자료를 쿼리하거나 업데이트하는 방법을 제공 

JDBC API 이용 시 DBMS의 종류에 상관없이 하나의 방법으로 작업 진행 가능 

 

[JDBC사용 객체]

  • DriverManager : 데이터 원본에 JDBC드라이버를 통하여 커넥션을 만드는 역할
  •                             getConnection()메소드를 사용, tcp/i[로 사용 
  • Connection
  • Statement 

[JDBC 드라이버로드]

패키지 import 및 클래스 로드 

<Statment 동작>

exeuteQuery : SELECT문과 같이 결과값이 여러 개의 레코드로 반환되는 경우 사용

exeuteUpdate : insert, update, delete문과 같이 테이블 내에 데이터 변경 후 반환하는 결과 값이 행의 개수인 경우 사용 

 

VO (Value Object): 데이터베이스의 각 컬럼을 저장하기 위한 클래스

DAO (database Access object) : dbms에 접속하여 실제 데이터를 전송하거나 경과 값을 전달 받는 클래스가 있는 패키지

connction pool (미적용) : 커넥션 풀이란 일정량의 connction 객체 (db 연결 객체)를 미리 만들어서 pool저장해줌

                                        -> 프레임워크를 사용해서 구현하는 것이 편함 

 

 

<EmpVO>

 

package com.kh.jdbc.vo;

import java.sql.Date;

// EMP Table에 대한 VO
public class EmpVO {
    private int empNO;
    private String name;
    private String job;
    private int mgr;
    private Date date;
    private double sal;
    private double comm;
    private int depthNO;

    public EmpVO(int empNO, String name, String job, int mgr, Date date, double sal, double comm, int depthNO) {
        this.empNO = empNO;
        this.name = name;
        this.job = job;
        this.mgr = mgr;
        this.date = date;
        this.sal = sal;
        this.comm = comm;
        this.depthNO = depthNO;
    }

    public int getEmpNO() {
        return empNO;
    }

    public void setEmpNO(int empNO) {
        this.empNO = empNO;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    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 getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public double getSal() {
        return sal;
    }

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

    public double getComm() {
        return comm;
    }

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

    public int getDepthNO() {
        return depthNO;
    }

    public void setDepthNO(int depthNO) {
        this.depthNO = depthNO;
    }

}

<common>

package com.kh.jdbc.util;

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

public class Common {
    final static String ORACLE_URL = "jdbc:oracle:thin:@localhost:1521:xe";
    final static String ORACLE_ID = "scott";
    final static String ORACLE_PW = "1234";
    final static String ORACLE_DRV = "oracle.jdbc.OracleDriver";

    public static Connection getConnection() {
        Connection conn = null;
        // null이면 접속 해제를 하지 말라는 조건을 넣을 수 있다
        try{
            Class.forName(ORACLE_DRV); // 드라이버 로딩
            // 연결 얻기
            conn = DriverManager.getConnection
                    (ORACLE_URL, ORACLE_ID, ORACLE_PW);
            System.out.println("오라클 DB 연결 성공");
        }catch (Exception e){
            e.printStackTrace();
            // 에러 리스트를 호출
        }
        return conn;
    }
    //해제 시 고려 해야할 사항
    public static void close(Connection conn) {
        try{
           if(conn != null && !conn.isClosed()){
               conn.close();
               System.out.println("연결 해제 성공");
           }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static void close(Statement stmt) {
        try{
            if(stmt != null && !stmt.isClosed()){
                stmt.close();
                System.out.println("Statement 해제 성공");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static void close(ResultSet rset) {
        try{
            if(rset != null && !rset.isClosed()){
                rset.close();
                System.out.println("ResultSet 해제 성공");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

<empDAO>

 

package com.kh.jdbc.dao;

import com.kh.jdbc.util.Common;
import com.kh.jdbc.vo.EmpVO;

import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// Query 문으로 DB의 정보를 가져옴
public class EmpDAO {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    Scanner sc = new Scanner(System.in);
    public List<EmpVO> empSelect(){
        List<EmpVO> list = new ArrayList<>();
        // arraylist가 조회할때는 유리하므로 linkedlist는 삽입/삭제 시 유리
        try{
            conn = Common.getConnection();
            // DB에 SQL문을 전달하여 실행 시키고 결과값을 반환 받기 위해 사용
            stmt = conn.createStatement();
            String sql = "SELECT * FROM EMP";
            rs = stmt.executeQuery(sql);
            while(rs.next()){
                int empNO = rs.getInt("EMPNO");
                String name = rs.getString("ENAME");
                String job = rs.getString("JOB");
                int mgr = rs. getInt("MGR");
                Date date = rs.getDate("HIREDATE");
                double sal = rs.getDouble("SAL");
                double comm = rs. getInt("COMM");
                int dept = rs.getInt("DEPTNO");
                EmpVO vo = new EmpVO(empNO, name, job, mgr, date, sal, comm, dept);
                list.add(vo); // 생성된 객체를 리스트에 저장
            }
            Common.close(rs);
            Common.close(stmt);
            Common.close(conn);

        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
    public void empInsert() {
        System.out.println("사원정보를 입력 하세요");
        System.out.print("사원번호(4자리) : ");
        int no = sc. nextInt();
        System.out.print("이름 : ");
        String name = sc.next();
        System.out.print("직책 : ");
        String job = sc.next();
        System.out.print("상관 사원번호(4자리) : ");
        int mgr = sc.nextInt();
        System.out.print("입사일 : ");
        String date = sc.next();
        System.out.print("급여 : ");
        int sal = sc.nextInt();
        System.out.print("성과급 : ");
        int comm = sc.nextInt();
        System.out.print("부서번호 : ");
        int dept = sc. nextInt();

        String sql = "INSERT INTO EMP(EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO) " +
                "VALUES(" + no + ", " + "'"+name+"'" +", "+"'"+job+"'"+", "+mgr+", "
                +"'"+date+"'"+", "+sal+", "+ comm +", "+ dept +")";
        try{
            conn = Common.getConnection();
            stmt = conn.createStatement();
            int ret = stmt.executeUpdate(sql);
            System.out.println("Return : "+ ret);
        }catch (Exception e){
            e.printStackTrace();
        }
        Common.close(stmt);
        Common.close(conn);
    }
        public void empUpdate() {
         System.out.println("변경할 사원 정보 입력");
         System.out.print("이름 : ");
         String name = sc.next();
         System.out.print("직책  : ");
         String job = sc.next();
         System.out.print("급여 : ");
         int sal = sc.nextInt();
         System.out.print("성과급 : ");
         int comm = sc.nextInt();

         String sql = "UPDATE EMP "
                 +"SET JOB = " + "'"+ job + "',"
                 +"SAL = "+ sal +","
                 +"COMM = "+comm + " "
                 +"WHERE ENAME = "+ "'"+name+ "'";
         try{
             conn = Common.getConnection();
             stmt = conn.createStatement();
             int ret = stmt.executeUpdate(sql);
             System.out.println("Return" + ret);
         }catch(Exception e){
             e.printStackTrace();
         }
         Common.close(stmt);
         Common.close(conn);
        }

        public void empDelete() {
        System.out.print("삭제할 이름을 입력하세요 : ");
        String name = sc.next();
        String sql = "DELETE FROM EMP WHERE ENAME =" + "'"+name+"'";
        try {
            conn = Common.getConnection();
            stmt = conn.createStatement();
            int ret = stmt.executeUpdate(sql);
        }catch (Exception e){
            e.printStackTrace();
        }
        Common.close(stmt);
        Common.close(conn);
        }


    public void empSelectRst(List<EmpVO> list){
        for(EmpVO e : list){
            System.out.print(e.getEmpNO()+ " ");
            System.out.print(e.getName()+ " ");
            System.out.print(e.getJob()+ " ");
            System.out.print(e.getMgr()+" ");
            System.out.print(e.getDate()+ " ");
            System.out.print(e.getSal()+ " ");
            System.out.print(e.getComm()+ " ");
            System.out.print(e.getDepthNO()+" ");
            System.out.println();

        }
    }
}

<jdbcMain>

 

package com.kh.jdbc;

import com.kh.jdbc.dao.EmpDAO;
import com.kh.jdbc.vo.EmpVO;

import java.util.List;
import java.util.Scanner;

public class JdbcMain {
    public static void main(String[] args) {
      menuSelect();
    }
    public static void menuSelect() {
        Scanner sc = new Scanner(System.in);
        EmpDAO dao = new EmpDAO();
        while (true){
            System.out.println("===== [EMP TABLE] =====");
            System.out.println("메뉴를 조회 하세요");
            System.out.print("[1]SELECT, [2]INSERT, [3]UPDATE, [4]DELETE,[5]EXIT : ");
            int sel = sc.nextInt();
            switch (sel){
                case 1 :
                    List<EmpVO> list = dao.empSelect();
                    dao.empSelectRst(list);
                    break;
                case 2:
                    dao.empInsert();
                    break;
                case 3:
                    dao.empUpdate();
                    break;
                case 4:
                    dao.empDelete();
                    break;
                case 5 :
                    System.out.println("메뉴를 종료 합니다.");
                    return;
            }
        }
    }
}

<prepareStatement()로 바꾸기>

 

package com.kh.jdbc.dao;

import com.kh.jdbc.util.Common;
import com.kh.jdbc.vo.EmpVO;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// Query 문으로 DB의 정보를 가져옴
public class EmpDAO {
    Connection conn = null;
    Statement stmt = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    Scanner sc = new Scanner(System.in);
    public List<EmpVO> empSelect(){
        List<EmpVO> list = new ArrayList<>();
        // arraylist가 조회할때는 유리하므로 linkedlist는 삽입/삭제 시 유리
        try{
            conn = Common.getConnection();
            // DB에 SQL문을 전달하여 실행 시키고 결과값을 반환 받기 위해 사용
            stmt = conn.createStatement();
            String sql = "SELECT * FROM EMP";
            rs = stmt.executeQuery(sql);
            while(rs.next()){
                int empNO = rs.getInt("EMPNO");
                String name = rs.getString("ENAME");
                String job = rs.getString("JOB");
                int mgr = rs. getInt("MGR");
                Date date = rs.getDate("HIREDATE");
                double sal = rs.getDouble("SAL");
                double comm = rs. getInt("COMM");
                int dept = rs.getInt("DEPTNO");
                EmpVO vo = new EmpVO(empNO, name, job, mgr, date, sal, comm, dept);
                list.add(vo); // 생성된 객체를 리스트에 저장
            }
            Common.close(rs);
            Common.close(stmt);
            Common.close(conn);

        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
    public void empInsert() {
        System.out.println("사원정보를 입력 하세요");
        System.out.print("사원번호(4자리) : ");
        int no = sc. nextInt();
        System.out.print("이름 : ");
        String name = sc.next();
        System.out.print("직책 : ");
        String job = sc.next();
        System.out.print("상관 사원번호(4자리) : ");
        int mgr = sc.nextInt();
        System.out.print("입사일 : ");
        String date = sc.next();
        System.out.print("급여 : ");
        int sal = sc.nextInt();
        System.out.print("성과급 : ");
        int comm = sc.nextInt();
        System.out.print("부서번호 : ");
        int dept = sc. nextInt();

        String sql = "INSERT INTO EMP(EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO) " +
                "VALUES(?,?,?,?,?,?,?,?)";
        try{
            conn = Common.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, no);
            pstmt.setString(2, name);
            pstmt.setString(3,job);
            pstmt.setInt(4,mgr);
            pstmt.setString(5,date);
            pstmt.setInt(6,sal);
            pstmt.setInt(7,comm);
            pstmt.setInt(8,dept);
            pstmt.executeUpdate();

        }catch (Exception e){
            e.printStackTrace();
        }
        Common.close(pstmt);
        Common.close(conn);
    }
        public void empUpdate() {
         System.out.println("변경할 사원 정보 입력");
         System.out.print("이름 : ");
         String name = sc.next();
         System.out.print("직책  : ");
         String job = sc.next();
         System.out.print("급여 : ");
         int sal = sc.nextInt();
         System.out.print("성과급 : ");
         int comm = sc.nextInt();

         String sql = "UPDATE EMP "
                 +"SET JOB = ?,SAL = ?,COMM = ? WHERE ENAME = ? ";
         try{
             conn = Common.getConnection();
             pstmt = conn.prepareStatement(sql);
             pstmt.setString(1,job);
             pstmt.setInt(2, sal);
             pstmt.setInt(3, comm);
             pstmt.setString(4, name);
             int ret = pstmt.executeUpdate();
             System.out.println("Return" + ret);
         }catch(Exception e){
             e.printStackTrace();
         }
         Common.close(pstmt);
         Common.close(conn);
        }

        public void empDelete() {
        System.out.print("삭제할 이름을 입력하세요 : ");
        String name = sc.next();
        String sql = "DELETE FROM EMP WHERE ENAME = ?";
        try {
            conn = Common.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,name);
            int ret = pstmt.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }
        Common.close(pstmt);
        Common.close(conn);
        }


    public void empSelectRst(List<EmpVO> list){
        for(EmpVO e : list){
            System.out.print(e.getEmpNO()+ " ");
            System.out.print(e.getName()+ " ");
            System.out.print(e.getJob()+ " ");
            System.out.print(e.getMgr()+" ");
            System.out.print(e.getDate()+ " ");
            System.out.print(e.getSal()+ " ");
            System.out.print(e.getComm()+ " ");
            System.out.print(e.getDepthNO()+" ");
            System.out.println();

        }
    }
}

----> 조별 테이블로 구현하기 

'국비학원 교육 일지' 카테고리의 다른 글

[38일차] 국비 교육  (1) 2022.09.13
[37일차] 국비 교육  (0) 2022.09.08
[34일차] 국비 교육  (0) 2022.09.05
[33일차] 국비 교육 - 객체  (0) 2022.09.02
[32일차] 국비 교육 - DDL, 제약 조건  (0) 2022.09.01