본문 바로가기

JAVA

231226 Java

코딩도장 1 ~ 9 까지의 값 중복 없이 출력해보기

최대한 빠르게

package study;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
// 경과 시간 확인 해보기
public class Study01 {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        // 1970 년 1 월 1 일부터 지금까지 밀리 초 반환 1 / 1000 초
        System.out.println("시작 : " + startTime);
        Set<Integer> set = new HashSet<>();
        while(true) {
            set.add((int)(Math.random() * 9 + 1));
            if (set.size() == 9) {
                break;
            }
        }
        Iterator<Integer> iterator = set.iterator();
        while(iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
        System.out.println();

        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            do {
                int j = (int)(Math.random() * 9 + 1);
                if (list.contains(j)) {
                    continue;
                } else {
                    list.add(j);
                }
            } while (list.size() != 9);
            System.out.println(list);
            list.clear();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("끝 : " + endTime);
        System.out.println("경과 시간 : " + (endTime - startTime));
    }
}

 

경과 시간 확인하기, 밀리초

package test;
// 경과 시간 확인하기
public class Test01 {
    public static void main(String[] args) {
        // 1970 년 1 월 1 일 이후 걸린 시간을 밀리 초로 반환
        long startTime = System.currentTimeMillis();
        System.out.println("시작 : " + startTime);

        long endTime = System.currentTimeMillis();
        System.out.println("끝 : " + endTime);
        System.out.println("걸린 시간 : " + (endTime - startTime));
    }
}

 

경과 시간 확인하기, 나노초

package test;
// 소요시간 확인 : 나노 초
public class Test02 {
    public static void main(String[] args) {
        long startTime = System.nanoTime();
        System.out.println("시작 : " + startTime);

        long endTime = System.nanoTime();
        System.out.println("끝 : " + endTime);
        System.out.println("소요 시간 : " + (endTime - startTime));
    }
}

 

예외처리

자바 내부가 아닌 외부에서 진행되는 입출력의 오류에 대비하는 처리

 

입력 시 data 가 없거나

출력 시 출력하는 경로가 잘못되었거나 할 때 처리하는 값

package test;
// 예외처리
// 데이터베이스와 자바를 붙여 사용해보기

/* 남은 것
 * 컬렉션 중 아직 안한 것 들
 * 중첩
 * 스레드
 * 입출력
 * 네트워크
 * GUI
 */
public class Study02 {
    public static void main(String[] args) {
        
    }
}

 

예외 처리

package com.poseidon.exception;
// Exception 예외
// 용어 : 예외, 오류, 핸들링, try catch, finally
/*
 * 자바에서는 예외라는 것을 두고 목적에 따라서 핸들링(처리)하도록 되어 있음
 * 예외는 주로 실행 시 발생하는 모든 에러 상황을 예외로 정의
 * 특정 API 는 컴파일 시 예외를 처리하지 않으면 컴파일이 되지 않음
 *
 * 예외의 정의
 * 실행 시 발생할 수 있는 모든 에러 상황으로 알아두기
 *
 * 예외가 발생하는 순서
 * 컴파일 → 실행 → 실행 중 예외 발생 → VM 이 발생한 예외의 종류/내용 파악 → 예외 객체 생성
 * → 발생한 코드 밖으로 예외 객체를 던짐(throw) → 예외의 콜 스택에 전이 → main 메소드 밖까지 던지면
 * 프로그램 비정상 종료
 *
 * Exception 이란 클래스의 하위타입이 바로 프로그래머가 처리할 예외타입
 * 예외 라고 표현할 때 최고 클래스로는 Exception 클래스를 말함
 * Throwable 클래스는 자식으로 Error 를 가지고 있기 때문에 예외의 최고 클래스라고 하지 않음
 *
 * 예외의 종류, 크게 2 가지로 나눌 수 있음
 *
 * 컴파일러가 관여하지 않으면서 실행 시 예외가 발생할 수 있는 예외
 * --→ 알려지지 않은 예외 (Unchecked Exception)
 * 컴파일러가 관여하는 예외
 * --→ 알려진 예외 (Checked Exception)으로 구분
 *
 * 구분 방법은 Exception 의 하위 클래스 중 RuntimeException 이 있음
 * 해당 클래스의 자식 클래스는 모두 알려지지 않은 예외, 나머지는 알려진 예외
 *
 */
public class Exception01 {
    public static void main(String[] args) {
        System.out.println("프로그램 시작");

        System.out.println("중간 로직");
        int num = 10;
        int num2 = 0;
        try {
            // 예외가 발생할 것 같은 문장
            System.out.println(num / num2);
        } catch (Exception e) {
            // 예외가 발생하면 처리할 문장
            System.out.println("예외 발생");
            System.out.println(e);
        }

        int arr[] = new int[]{1,2,3};
        System.out.println(arr[0]);
        System.out.println(arr[1]);
        System.out.println(arr[2]);
        try {
            System.out.println(arr[3]); // 오류 발생 시 try 문을 건너뛰고 catch 문 실행
            System.out.println(1 / 0);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("배열 길이 밖으로 나감");
            System.out.println(e);
        }
        System.out.println("프로그램 끝");
    }
}

 

예외 처리 finally

package com.poseidon.exception;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Exception02 {
    public static void main(String[] args) {
        FileReader fileReader = null;
        try {
            fileReader = new FileReader("temp.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("파일이 없습니다");
        } finally {
            // 예외 발생과 상관없이 실행할 문장
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("");
            }
        }
        System.out.println("프로그램 종료");
    }
}

 

DB 와 Java 연결하기

package study;

import java.sql.*;

public class dbStudy {
    public static void main(String[] args) {
        Connection conn = null; // Connection : DB와 연결하기 위한 인터페이스
        PreparedStatement pstmt = null; // 특정한 SQL에 대한 통로
        ResultSet rs = null; // SQL문의 결과를 저장하는 객체
        String db = "jdbc:mariadb://-----";
        String id = "-----";
        String pw = "-----";
        String sql = "SELECT * FROM departments";

        try {
            Class.forName("org.mariadb.jdbc.Driver");
            conn = DriverManager.getConnection(db, id, pw); // DriverManager : JDBC 드라이버 로드
            pstmt = conn.prepareStatement(sql); 
            rs = pstmt.executeQuery();

            while(rs.next()) { // rs 에 값이 있으면 true
                String dept_no = rs.getString("dept_no");
                String dept_name = rs.getString("dept_name");
                System.out.println(dept_no + " : " + dept_name);
            }
        } catch (ClassNotFoundException e) {
            System.out.println("클래스를 찾지 못함");
        } catch (SQLException e) {
            System.out.println("접속 정보를 확인");
        } finally {
            try {
                rs.close();
                pstmt.close();
                conn.close();
            } catch (SQLException e) {
                System.out.println("에러");
            }
        }
    }
}

 

한 클래스에서 처리한 내용 중 계속 사용되는 파일 클래스로 따로 만들기

package com.poseidon.db;

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

// 접속 정보만 가지고 있는 클래스
// 나중에 싱글턴으로 체크할 것
public class DBConnection {
    public Connection getConnection() {
        Connection con = null;
        try {
            Class.forName("org.mariadb.jdbc.Driver");
            String url = "jdbc:mariadb://-----";
            String id = "-----";
            String pw = "-----";
            con = DriverManager.getConnection(url, id, pw);
        } catch (ClassNotFoundException | SQLException e) {
            System.out.println(e);
            System.out.println("오류 발생");
        }
        return con;
    }

}

 

package com.poseidon.db;
// 데이터 전송 객체
public class EmployeesDTO {
    // 값을 담을 변수
    private String dept_no, dept_name; // DTO 에서 필드는 private 필수

    // Getter, Setter method
    public String getDept_no() {
        return dept_no;
    }

    public void setDept_no(String dept_no) {
        this.dept_no = dept_no;
    }

    public String getDept_name() {
        return dept_name;
    }

    public void setDept_name(String dept_name) {
        this.dept_name = dept_name;
    }
}

 

package com.poseidon.db;

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

public class EmployeesDAO {
    public List<EmployeesDTO> selectDepartments() {
        List<EmployeesDTO> result = null;
        // 데이터베이스 접속 정보
        DBConnection dbConn = new DBConnection();
        Connection conn = dbConn.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        // SQL
        String sql = "SELECT * FROM departments";
        try {
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while(rs.next()) {
                // String dept_no = rs.getString(1); // SQL 의 index 는 1 부터 시작
                // String dept_name = rs.getString(2);
                // System.out.println(dept_no + " : " + dept_name);
                EmployeesDTO employeesDTO = new EmployeesDTO();
                employeesDTO.setDept_no(rs.getString("dept_no"));
                employeesDTO.setDept_name(rs.getString("dept_name"));
                result.add(employeesDTO);
            }
        } catch (SQLException e) {
            System.out.println("오류 발생" + e) ;
        } finally {
            try {
                rs.close();
                pstmt.close();
                conn.close();
            } catch (SQLException e) {
                System.out.println("오류 발생");
            }
        }
        // 데이터 만드는 작업
        return result;
    }
}

 

실행 구문

package com.poseidon.db;

import java.util.List;

public class Test03 {
    public static void main(String[] args) {
        EmployeesDAO dao = new EmployeesDAO();

        List<EmployeesDTO> result = dao.selectDepartments();
        for (int i = 0; i < result.size(); i++) {
            System.out.print(result.get(i).getDept_no() + " : ");
            System.out.println(result.get(i).getDept_name());
        }
    }
}

 

추가로 해보기

package com.poseidon.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class EmployeesDAO {
    DBConnection dbConn = new DBConnection();
    public List<EmployeesDTO> selectEmployees() {
        List<EmployeesDTO> result = null;
        Connection conn = dbConn.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql = "SELECT * FROM employees Limit 10, 10";
        try {
            pstmt = conn.prepareStatement(sql); // sql 에 있는 문장으로 연결
            rs = pstmt.executeQuery(); // select 문 실행
            result = new ArrayList<>();
            while (rs.next()) {
                EmployeesDTO dto = new EmployeesDTO();
                dto.setEmp_no(rs.getInt("emp_no"));
                dto.setBirth_date(rs.getString("birth_date"));
                dto.setFirst_name(rs.getString("first_name"));
                dto.setLast_name(rs.getString("last_name"));
                // dto.setGender((char)rs.getInt("gender"));
                dto.setGender(rs.getString("gender"));
                dto.setHire_date(rs.getString("hire_date"));
                result.add(dto);
            }
        } catch (SQLException e) {
            System.out.println(e);
            System.out.println("오류 발생 DTO 설정");
        } finally {
            try {
                rs.close();
                pstmt.close();
                conn.close();
            } catch (SQLException e) {
                System.out.println("오류 발생 : close()");
            }
        }

        return result;
    }
    public List<EmployeesDTO> selectDepartments() {
        List<EmployeesDTO> result = null;
        // 데이터베이스 접속 정보
        Connection conn = dbConn.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        // SQL
        String sql = "SELECT * FROM departments";
        try {
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            result = new ArrayList<>();
            while(rs.next()) {
//                String dept_no = rs.getString(1);
//                String dept_name = rs.getString(2);
//                System.out.println(dept_no + " : " + dept_name);
                EmployeesDTO employeesDTO = new EmployeesDTO();
                employeesDTO.setDept_no(rs.getString("dept_no"));
                employeesDTO.setDept_name(rs.getString("dept_name"));
                result.add(employeesDTO);
            }
        } catch (SQLException e) {
            System.out.println("오류 발생" + e) ;
        } finally {
            try {
                rs.close();
                pstmt.close();
                conn.close();
            } catch (SQLException e) {
                System.out.println("오류 발생");
            }
        }
        // 데이터 만드는 작업
        return result;
    }
}

 

package com.poseidon.db;

import java.util.List;

public class Test03 {
    public static void main(String[] args) {
        EmployeesDAO dao = new EmployeesDAO();
        dao.selectDepartments();

        List<EmployeesDTO> result = dao.selectDepartments();
        for (int i = 0; i < result.size(); i++) {
            System.out.print(result.get(i).getDept_no() + " : ");
            System.out.println(result.get(i).getDept_name());
        }
        List<EmployeesDTO> result2 = dao.selectEmployees();
        for (int i = 0; i < result2.size(); i++) {
            System.out.print(result2.get(i).getEmp_no() + " : ");
            System.out.print(result2.get(i).getBirth_date() + " : ");
            System.out.print(result2.get(i).getFirst_name() + " : ");
            System.out.print(result2.get(i).getLast_name() + " : ");
            System.out.print(result2.get(i).getGender() + " : ");
            System.out.println(result2.get(i).getHire_date());
        }
    }
}

'JAVA' 카테고리의 다른 글

240103 Java  (0) 2024.01.03
231227 Java  (0) 2023.12.27
231222 Java  (0) 2023.12.22
231221 Java  (2) 2023.12.21
231220 Java  (0) 2023.12.20