Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
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
Tags
more
Archives
Today
Total
관리 메뉴

rudu_std

JDBC 본문

Java

JDBC

Ru_Du 2024. 8. 1. 01:15
package edu.java.jdbc;

import com.mysql.cj.protocol.Resultset;

import java.sql.*;

public class JDBCTest {

    private Connection con; // DB 연결 객체
    private Statement stmt; // 쿼리 실행 객체

    public JDBCTest(){
        // mysql 접속 정보 및 스키마
        String url = "jdbc:mysql://localhost:3306/modeldb";
        String username = "root";   // mysql 접속 계정
        String password = "0813";   //      "         의 비밀번호

        // Connection 객체 생성 - DriveManager 이용
        try {
            con = DriverManager.getConnection(url, username, password);
            System.out.println("con ok");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void insert(){   // t_member 테이블에 레코드 추가 --------------------
        // 회원아이디, 회원이름, 비밀번호, 이메일, 성별, 사진, 생년월일, 가입일자
        // aaa         김이박      1111   a@a.com  F    a.png 1999-09-09 지금
        // bbb         비비비      2222   b@b.com  M    b.png 2000-01-01 지금
        String query = " INSERT INTO t_member() VALUES( 'aaa', '김이박', 1111, 'a@a.com', " +
                " 'F', 'a.png', '1999-09-09', now()) ";
        
        query = """
                 INSERT INTO t_member
                 VALUES( 'bbb', '김비비', 1111, 'b@b.com', 'M', 'b.png', '2000-01-01', now())
                """ ;
        try {
            stmt = con.createStatement();   // 쿼리 실행 객체 생성
            int result = stmt.executeUpdate(query);      // 쿼리 실행
            if(result == 1){    // 추가 성공
                System.out.println("insert ok");
            }else{
                System.out.println("insert not ok");
            }
        } catch (SQLException e) {
            System.err.println("insert 쿼리 실행 실패");
            System.err.println(e.getErrorCode() + " | " +  e.getMessage());
            System.err.println("--------------------------------------------------");
            throw new RuntimeException(e);
        } finally { // 예외 발생 여부 관계없이 항상 실행
            try {
                if( stmt != null ) stmt.close();   //쿼리 실행 객체 닫기
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        

    }

    public void select(String id){   // t_member 테이블의 레코드 조회 --------------------
        //회원아이디가 aaa인 레코드
        String query = " SELECT * FROM t_member WHERE MID = ? ";
        ResultSet rs = null;
        try (PreparedStatement pstmt                 // 쿼리 실행 객체 생성
                     = con.prepareStatement(query)){ // 쿼리문을 미리 준비

            pstmt.setString(1, id);    // 쿼리의 물픔표에 해당하는 값 바인딩
            rs = pstmt.executeQuery();                    // 쿼리 실행 후 결과 받기
            
            
            
            /////////////////////////////////////////////////////////////////////////////
            //rs가 밖에 있는이유 : try 안에 선언을 하면 try가 끝날때 같이 사라지기에 밖에둔다
            /////////////////////////////////////////////////////////////////////////////
            
            
            
            if( rs.next()){// 읽어올 값이 있는지 확인
                System.out.println("----- 회원 정보 -----");
                System.out.println("회원 아이디 : " + rs.getString("mid"));
                System.out.println("회원 이름 : " + rs.getString("mname"));
                System.out.println("이메일 : " + rs.getString("email"));
                System.out.println("성별 : " + rs.getString("gender"));
                System.out.println("사진 : " + rs.getString("photo"));
                System.out.println("생년월일 : " + rs.getString("birth_date"));
                System.out.println("가입일자 : " + rs.getString("join_date"));
            } else {    // 읽어올 값이 없는 경우
                System.out.println(" - 일치하는 회원 정보가 없습니다. - ");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(rs != null) rs.close();
            }catch (SQLException e){
                throw new RuntimeException(e);
            }
        }


    }

    public void selectAll(){    // t_member 테이블의 모든 레코드 조회 --------------------
        String query = " SELECT * FROM t_member ";

        System.out.println("==================== 전체 회원 목록 ====================");
        System.out.println("아이디\t | 이름\t | 이메일\t | 가입일자\t");
        ResultSet rs = null;
        try (PreparedStatement pstmt                 // 쿼리 실행 객체 생성
                     = con.prepareStatement(query)){ // 쿼리문을 미리 준비

            rs = pstmt.executeQuery();                    // 쿼리 실행 후 결과 받기

            while(rs.next()){
                System.out.print(rs.getString("mid") + "\t\t");
                System.out.print(rs.getString("mname") + "\t\t");
                System.out.print(rs.getString("email") + "\t\t");
                System.out.print(rs.getString("join_date") + "\t\t");
                System.out.println();
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(rs != null) rs.close();
            }catch (SQLException e){
                throw new RuntimeException(e);
            }
        }


        System.out.println("========================================================");

    }

    public void update(){   // t_member 테이블의 회원아이디가 bbb인 레코드 변경 --------------------
        // 이메일 : aaa@aaa.com, 사진 : aaa.png
        String query = " UPDATE t_member SET EMAIL = 'bbb@bbb.com', PHOTO = 'bbb.png' WHERE MID = 'bbb' ";

        try (Statement stmt = con.createStatement()){// 쿼리 실행 객체 생성
                                                     // try with resources이용 - 별도의 닫기 처리 불필요
            int result = stmt.executeUpdate(query);
            if(result == 1) System.out.println("update ok");
            else            System.out.println("update not ok");
        }catch (SQLException e){
            throw new RuntimeException(e);
        }
    }

    public void delete(String id){   // t_member 테이블의 회원아이디를 매개변수로 받아 레코드 삭제 --------------------
        String query = " DELETE FROM t_member WHERE MID = '" + id + "' ";

        try (Statement stmt = con.createStatement()){// 쿼리 실행 객체 생성
            // try with resources이용 - 별도의 닫기 처리 불필요
            int result = stmt.executeUpdate(query);
            if(result == 1) System.out.println("delete ok");
            else            System.out.println("delete not ok");
        }catch (SQLException e){
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {

        JDBCTest jt = new JDBCTest();
        // id bbb를 매개변수로 전달하여 delete 메서드 호출
//        jt.delete("bbb");
//        jt.insert();
//        jt.select("aaa");
        jt.selectAll();
//        jt.update();

    }
}

'Java' 카테고리의 다른 글

stream && Ramda  (0) 2024.09.03
JDBC 정리  (0) 2024.08.02
람다 표현식 (Lambda Expression)  (0) 2024.07.24
클래스 형변환  (0) 2024.07.24
static  (0) 2024.07.21