- 싱글톤 패턴

디자인 패턴 중 하나로 매번 드라이버를 로드하지 않고 프로세스에서 객체를 단 하나만 만들어서 공유 자원을 생성하는 기법을 의미한다.

 

 

✔️ 디자인 패턴

소프트웨어를 설계할 때 특정 맥락에서 자주 발생하는 고질적인 문제들이 발생했을 때 재사용할 수 있는 해결책을 다룬 알고리즘이다.

 

 


-PreparedStatment 인터페이스

Statement와 PreparedStatement의 차이는 캐시 사용 유무이다.

객체를 캐시에 담아서 재사용한다.

반복적으로 쿼리를 수행한다면 statement에 비해 성능이 많이 좋다.

statement는 보안상 취약점이 발견되었기 때문에 PreparedStatement를 사용하는 것을 권장한다.

단점으로는 코드가 길어질 수 있다.

 

// Statement 사용시
StringBuilder sql = new StringBuilder();
sql.append ...

// PreparedStatement 사용시
  StringBuilder sql = new StringBuilder();
  sql.append("delete from tb_member ").append("WHERE mem_userid=?");

  PreparedStatement pstmt = conn.PreparedStatement(sql.toString);
  pstmt.setString(1,mem_userid)
  pstmt.executeUpdate();

 

- ResultSet 인터페이스

결과를 저장할 수 있는 객체이다.

저장된 값을 row 단위로 불러올 수 있다.

row단위로 데이터를 가져올 경우 타입을 지정하여 가져올 수 있다.

 

 

- DTO (Data Transfer Object)

계층 간 데이터를 교환하기 위한 자바 빈즈를 의미한다.

순수한 데이터 객체이다.

getter, setter 메소드가 존재한다.

DTO와 VO (Value Object)를 혼용해서 사용하는 경우가 많다. (VO : 읽기 전용, getter 메소드만 존재)

 

 

- DAO (Data Access Object)

데이터 베이스의 데이터에 접근하기 위해 생성하는 객체이다.

데이터 베이스에 접근하기 위한 로직이나 비즈니스 로직을 분리하기 위해서 사용한다.

DB에 접근하여 데이터의 CRUD(생성, 읽기, 갱신, 삭제) 작업을 하는 클래스이다.

코드의 간결화 및 모듈화, 유지보수등의 목적을 위해 생성하여 사용하는 것을 권장한다.

DB를 사용하여 데이터의 조회 및 조작하는 기능을 전담하는 오브젝트이다.

 

 


PreparedStatement 인터페이스를 사용해서 영어 단어장 만들기!

 

 

DBconn 클래스 (싱글톤 패턴)

package Day12;

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

public class DBconn {
    private static Connection conn;

    public static Connection getConnection() throws SQLException, ClassNotFoundException {
        String url = "jdbc:mysql://ip주소 혹은 localhost:3306/devwork?useSSL=false";
        String userid = "mysql user입력";
        String userpw = "userpw 입력";

        Class.forName("com.mysql.cj.jdbc.Driver");
        conn = DriverManager.getConnection(url,userid,userpw);

        return conn;
    }
}

 

 

VocaDAO

package Day12;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class VocaDAO {
    public void insert() throws SQLException, ClassNotFoundException {
        Scanner sc = new Scanner(System.in);
        System.out.print("등록할 영어단어를 입력하세요 : ");
        String eng = sc.next();
        System.out.print("한글 뜻을 입력하세요 : ");
        String kor = sc.next();
        System.out.print("등록할 단어의 레벨을 입력하세요 : ");
        int lev = sc.nextInt();

        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO tb_word (eng, kor, lev)").append(" VALUES (?, ?, ?)");

        Connection conn = DBconn.getConnection();
        PreparedStatement pstmt = conn.prepareStatement(sql.toString());

        pstmt.setString(1, eng);
        pstmt.setString(2, kor);
        pstmt.setInt(3, lev);

        int result = pstmt.executeUpdate();

        if(result >= 1) System.out.println("✔ 단어 등록이 완료 되었습니다!");
        else System.out.println("다시 시도해주세요....");

    }

    public void list() throws SQLException, ClassNotFoundException{
        Connection conn = DBconn.getConnection();

        StringBuilder sql = new StringBuilder();
        sql.append("SELECT eng, kor, lev,rdate FROM tb_word ORDER BY eng");

        PreparedStatement pstmt = conn.prepareStatement(sql.toString());
        ResultSet rs = pstmt.executeQuery();

        VocaDTO listDTO = new VocaDTO();

        while(rs.next()) {
            String eng = rs.getString("eng");
            String kor = rs.getString("kor");
            int lev = rs.getInt("lev");
            String rdate = rs.getString("rdate");

            System.out.println(eng + " : " +kor + " (" + lev+", "+rdate+")");
        }

    }
    public void search() throws SQLException, ClassNotFoundException{
        Scanner sc = new Scanner(System.in);
        System.out.print("찾을 영단어를 입력하세요 : ");
        String word = sc.next();

        boolean isFind = false;
        Connection conn = DBconn.getConnection();

        StringBuilder sql = new StringBuilder();
        sql.append("SELECT eng,kor,lev FROM tb_word WHERE eng LIKE ? ");
        PreparedStatement pstmt = conn.prepareStatement(sql.toString());
        pstmt.setString(1,"%"+word+"%");

        ResultSet rs = pstmt.executeQuery();

        while (rs.next()) {
            isFind = true;
            String eng = rs.getString("eng");
            String kor = rs.getString("kor");
            int lev = rs.getInt("lev");
            System.out.println(eng + " : " +kor + ","+lev);
        }
        if(!isFind) System.out.println("찾는 단어가 없습니다. 😥");
    }

    public void modify() throws SQLException,ClassNotFoundException {
        Scanner sc = new Scanner(System.in);
        System.out.print("수정할 영단어를 입력하세요 : ");
        String word = sc.next();
        System.out.print("수정할 영단어의 한글 뜻을 입력하세요 : ");
        String kor = sc.next();
        System.out.print("수정할 영단어의 레벨을 입력하세요 : ");
        int lev = sc.nextInt();

        Connection conn = DBconn.getConnection();
        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE tb_word SET kor = ?, lev = ? where eng = ? ");
        PreparedStatement pstmt = conn.prepareStatement(sql.toString());
        pstmt.setString(1,kor);
        pstmt.setInt(2,lev);
        pstmt.setString(3, word);

        int result = pstmt.executeUpdate();

        if(result >= 1) System.out.println("수정완료!");
        else System.out.println("수정실패..");
    }

    public void delete() throws SQLException, ClassNotFoundException {
        Scanner sc = new Scanner(System.in);
        System.out.print("삭제할 영단어를 입력하세요 : ");
        String word = sc.next();

        StringBuilder sql = new StringBuilder();
        sql.append("DELETE FROM tb_word WHERE eng = ?");

        Connection conn = DBconn.getConnection();
        PreparedStatement pstmt = conn.prepareStatement(sql.toString());
        pstmt.setString(1, word);

        int result = pstmt.executeUpdate();
        if(result >= 1) System.out.println("삭제완료!");
        else System.out.println("삭제 실패..");
    }
}

 

 

main 메소드

package Day12;

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

public class VocaMain {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        VocaDAO vdao = new VocaDAO();

        while(true) {
            System.out.println("📒📘 영어단어장 📘📒");
            System.out.println("원하는 메뉴를 선택하세요.");
            System.out.println("1. 등록 2. 리스트 3. 검색 4. 수정 5. 삭제 6. 종료");
            int input = sc.nextInt();

            if(input == 6) {
                System.out.println("단어장을 끕니다!!");
                break;
            }

            switch (input) {
                case 1:
                    try {
                        vdao.insert();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    break;
                case 2:
                    try {
                        vdao.list();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    break;
                case 3:
                    try {
                        vdao.search();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    break;
                case 4:
                    try {
                        vdao.modify();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    break;
                case 5:
                    try {
                        vdao.delete();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }
}

 

 

위 코드의 결과

 

'국비 > JAVA' 카테고리의 다른 글

DAY 11 : JDBC  (0) 2022.10.27
DAY 10 : 스레드(Thead)  (0) 2022.10.21
DAY 09 - 2 : 파일 입출력  (0) 2022.10.13
DAY 09 - 1: 중첩 클래스, 예외 처리  (0) 2022.10.12
DAY 08 - 2 : 컬렉션 프레임워크 (Set, Map)  (0) 2022.10.12
복사했습니다!