ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JDBC(Java Database Connectivity)-22.04.11
    고급자바 2022. 4. 11. 13:37
    728x90

    <인터페이스> 드라이버를 통해서....접근

    ① Connection 

    ② Statement

    ③ PreparedStatment

    ④ ResultSet -결과값을 받아오기 위해 

    =>이 4가지 인터페이스 기반으로 하는것이 바로 JDBC이다!!!!!

    먼저 DB에 테이블 생성!


    <드라이버 준비하기>

    D:\C_Lib\ibatis 경로에 접속

    복사해서 사용할 프로젝트에 넣어주기

     

     

    Build Path에도 추가를 해준다.

    Add JARs...를 눌러서 ojdbc6.jar를 추가해준다.

    =>잘 가져온것을 알 수 있다.


    2번은 JDBC를 로딩하고 Connection하는것인데 앞으로 자주 사용해야하므로 따로 만들어주었다.

    <JDBC드라이버를 로딩하고 Connection객체를 생성하는 메서드로 구성된 클래스>

    package kr.or.ddit.util;
    
    import java.sql.Statement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    /**
     * JDBC드라이버를 로딩하고 Connection객체를 생성하는 메서드로 구성된 클래스
     *
     */
    public class JDBCUtil {
    	static {
    		try {
    			Class.forName("oracle.jdbc.driver.OracleDriver"); //클래스 정보 있는지 없는지 확인 , 즉 필드패쓰 잘 잡았는지도 확인해줌
    			System.out.println("드라이버 로딩 성공!");
    		} catch (ClassNotFoundException e) {
    			System.out.println("드라이버 로딩 실패!!!");
    			e.printStackTrace();
    		}
    	}
    	
    	public static Connection getConnection() {
    		try {
    			return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
    					"LAI",
    					"java");
    		}catch(SQLException e) {
    			System.out.println("DB 연경 실패!!!");
    			e.printStackTrace();
    			return null;
    		}
    	}
    	
    	//자원반납
    	public static void close(Connection conn, Statement stmt, PreparedStatement pstmt, ResultSet rs) {
    		if(rs !=null) try {rs.close();}catch(SQLException ex) {}
    		if(pstmt !=null) try {pstmt.close();}catch(SQLException ex) {}
    		if(stmt !=null) try {stmt.close();}catch(SQLException ex) {}
    		if(conn !=null) try {conn.close();}catch(SQLException ex) {}
    		
    	}
    
    }

    <static블록>

    객체를 생성하지 않고도 static객체를 접근할 수 있다. 공유가 가능하고 객체에 손쉽게 접근 가능

    클래스가 로딩됐을때 호출됐을 때 한번만 호출이된다

     

     

    <쿼리를 생성해서 실행하기위한 목적>

    try {
    			conn = JDBCUtil.getConnection();
    			String sql="insert into mymember" 
    					 + " (mem_id, mem_name, mem_tel, mem_addr)" 
    					 + " values "
    					 + " (?, ?, ?, ?)";
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1,memId);
    			pstmt.setString(2,memName);
    			pstmt.setString(3,memTel);
    			pstmt.setString(4,memAddr);
    			
    			int cnt = pstmt.executeUpdate();   //해당쿼리가실행하고나서 실행된 수를 리턴함 즉 위에것이 실행되면 1이 리턴될 것임.
    			
    			if(cnt > 0) {
    				System.out.println(memId + "회원 추가 작업 성공!");
    			}else {
    				System.out.println(memId + "회원 추가 작업 실패!!!");
    			}
    	
    		}catch(SQLException ex) {
    			System.out.println(memId + "회원 추가 작업 실패!!!");
    			ex.printStackTrace();
    		}finally {
    			
    		}
    		
    	}

     

    ExecuteQuery

     

    1. 수행결과로 ResultSet 객체의 값을 반환합니다.

    2. SELECT 구문을 수행할 때 사용되는 함수입니다.

     

    ExecuteUpdate

     

    1. 수행결과로 Int 타입의 값을 반환합니다.

    2. SELECT 구문을 제외한 다른 구문을 수행할 때 사용되는 함수입니다.

     


    <메뉴를 출력하는 메서드>

    <프로그램 시작 메서드>

    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Scanner;
    
    import kr.or.ddit.util.JDBCUtil;
    
    public class T01_MemberInfoTest {
    	
    	private Connection conn;
    	private Statement stmt;
    	private PreparedStatement pstmt;
    	private ResultSet rs;
    	
    	private Scanner scan = new Scanner(System.in); 
    	
    	/**
    	 * 메뉴를 출력하는 메서드
    	 */
    	public void displayMenu(){
    		System.out.println();
    		System.out.println("----------------------");
    		System.out.println("  === 작 업 선 택 ===");
    		System.out.println("  1. 자료 입력");
    		System.out.println("  2. 자료 삭제");
    		System.out.println("  3. 자료 수정");
    		System.out.println("  4. 전체 자료 출력");
    		System.out.println("  5. 작업 끝.");
    		System.out.println("----------------------");
    		System.out.print("원하는 작업 선택 >> ");
    	}
    	
    	/**
    	 * 프로그램 시작메서드
    	 */
    	public void start(){
    		int choice;
    		do{
    			displayMenu(); //메뉴 출력
    			choice = scan.nextInt(); // 메뉴번호 입력받기
    			switch(choice){
    				case 1 :  // 자료 입력
    					insertMember();
    					break;
    				case 2 :  // 자료 삭제
    				
    					break;
    				case 3 :  // 자료 수정
    				
    					break;
    				case 4 :  // 전체 자료 출력
    			
    					break;
    				case 5 :  // 작업 끝
    					System.out.println("작업을 마칩니다.");
    					break;
    				default :
    					System.out.println("번호를 잘못 입력했습니다. 다시입력하세요");
    			}
    		}while(choice!=5);
    	}

    <회원 추가하는 메서드>  case 1

    private void insertMember() {
    		boolean chk = false; //등록여부 체크용.
    		String memId = "";
    		
    		do {
    			
    			System.out.println();
    			System.out.println("추가할 회원정보를 입력하세요.");
    			System.out.print("회원ID >> ");
    			
    			memId = scan.next();
    			chk = checkMember(memId);  //중복 체크
    			
    			if(chk == true) { //true: 회원이 이미 있는경우를 말함
    				System.out.println("회원 ID가 "+memId + "인 회원은 이미 존재합니다.");
    				System.out.println("다시 입력하세요.");
    			}
    			
    		} while (chk==true); 
    		
    		System.out.print("회원 이름>> ");
    		String memName = scan.next();
    		
    		System.out.print("회원 전화번호>> ");
    		String memTel = scan.next();
    		
    		scan.nextLine();  //버퍼지우기
    		
    		System.out.print("회원 주소>> ");
    		String memAddr = scan.nextLine();
    		
    		try {
    			conn = JDBCUtil.getConnection();
    			String sql="insert into mymember" 
    					 + " (mem_id, mem_name, mem_tel, mem_addr)" 
    					 + " values "
    					 + " (?, ?, ?, ?)";
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1,memId);
    			pstmt.setString(2,memName);
    			pstmt.setString(3,memTel);
    			pstmt.setString(4,memAddr);
    			
    			int cnt = pstmt.executeUpdate();   //해당쿼리가실행하고나서 실행된 수를 리턴함 즉 위에것이 실행되면 1이 리턴될 것임.
    			
    			if(cnt > 0) {
    				System.out.println(memId + "회원 추가 작업 성공!");
    			}else {
    				System.out.println(memId + "회원 추가 작업 실패!!!");
    			}
    	
    		}catch(SQLException ex) {
    			System.out.println(memId + "회원 추가 작업 실패!!!");
    			ex.printStackTrace();
    		}finally {
    			JDBCUtil.close(conn, stmt, pstmt, rs);
    		}
    		
    	}

    <회원ID를 이용하여 회원이 존재하는지 알려주는 메서드 
     * @param memId 회원ID
     * @return true: 회원이 존재함, false: 회원이 존재하지 않음.>

    private boolean checkMember(String memId) {
    		boolean chk = false; //회원 존재여부 체크
    		
    		try {
    			conn = JDBCUtil.getConnection();
    			
    			String sql = "select count(*) as cnt from mymember"
    					+ "  where mem_id = ?";
    			
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, memId);
    			
    			rs = pstmt.executeQuery();  //ResultSet에 객체를 담는다.
    			
    			int cnt=0;
    			while(rs.next()) {  //가져올 값들이 여러건인 경우 while 한개인경우 if(rs.next())
     				cnt = rs.getInt("CNT");
    			}
    			if(cnt>0) {  //0보다 크면 중복이 있다!
    				chk = true;
    			}
    			
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}finally {
    			JDBCUtil.close(conn, stmt, pstmt, rs);
    		}
    		return chk;  //중복이면 true 중복이 아니면 false가 리턴됨 
    	}
    
    	public static void main(String[] args) {
    		T01_MemberInfoTest memObj = new T01_MemberInfoTest();
    		memObj.start();
    	}
    
    }

    <회원삭제하는 메소드> case2

    /**
    	 * 회원정보를 삭제하기 위한 메서드
    	 */
    	private void deleteMember() {
    		System.out.println();
    		System.out.println("삭제할 회원정보를 입력하세요.");
    		System.out.print("회원ID >> ");
    		
    		String memId = scan.next();
    		
    		try {
    			conn=JDBCUtil.getConnection();
    			
    			String sql = "delete from mymember where mem_id= ?";
    			
    			pstmt =conn.prepareStatement(sql);
    			
    			pstmt.setString(1,memId);
    			
    			int cnt =pstmt.executeUpdate();
    			
    			if(cnt > 0){
    				System.out.println(memId + "회원정보를 삭제했습니다.");
    			}else {
    				System.out.println(memId + "회원정보를 삭제 실패!!!");
    			}
    			
    		}catch(SQLException e){
    			System.out.println(memId + "회원정보를 삭제 실패!!!");
    			e.printStackTrace();
    		}finally {
    			JDBCUtil.close(conn, stmt, pstmt, rs);
    		}
    		
    	}

    <회원업데이트 메소드> case3

    /**
    	 * 회원 정보 수정하기 위한 메서드
    	 */
    	private void updateMember() {
    		
    		boolean chk = false; //등록여부 체크용.
    		String memId = "";
    		
    		do {
    			
    			System.out.println();
    			System.out.println("수정할 회원정보를 입력하세요.");
    			System.out.print("회원ID >> ");
    			
    			memId = scan.next();
    			chk = checkMember(memId);  //중복 체크
    			
    			if(chk == false) { //true: 회원이 이미 있는경우를 말함
    				System.out.println("회원 ID가 "+memId + "인 회원은 존재하지 않습니다.");
    				System.out.println("다시 입력하세요.");
    			}
    			
    		} while (chk==false); //중복된 애가 있어야 업데이트 가능
    		
    		System.out.print("회원 이름>> ");
    		String memName = scan.next();
    		
    		System.out.print("회원 전화번호>> ");
    		String memTel = scan.next();
    		
    		scan.nextLine();  //버퍼지우기
    		
    		System.out.print("회원 주소>> ");
    		String memAddr = scan.nextLine();
    		
    		try {
    			conn=JDBCUtil.getConnection();
    			
    			String sql = "update mymember" 
    					+  " set mem_name = ?,"  
    					+  " mem_tel = ?,"  
    					+  " mem_addr= ?"  
    					+  " where mem_id = ?";
    			
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, memName);
    			pstmt.setString(2, memTel);
    			pstmt.setString(3, memAddr);
    			pstmt.setString(4, memId);
    			
    			int cnt = pstmt.executeUpdate();
    			
    			if(cnt > 0) {
    				System.out.println(memId + "회원의 정보를 수정했습니다.");
    			}else {
    				System.out.println("회원의 정보를 수정실패!!!");
    			}
    			
    		}catch(SQLException e){
    			System.out.println("회원의 정보를 수정실패!!!");
    			e.printStackTrace();
    		}finally {
    			JDBCUtil.close(conn, stmt, pstmt, rs);
    		}
    	}

    <회원 정보 출력 메소드>case4

    /**
    	 * 전체 회원 정보를 출력하는 메서드
    	 */
    	private void displayMemberAll() {
    		System.out.println();
    		System.out.println("--------------------------------------------------");
    		System.out.println("ID\t이름\t전화번호\t\t\t 주 소");
    		System.out.println("--------------------------------------------------");
    		
    		try {
    			conn=JDBCUtil.getConnection();
    			
    			String sql = "select * from mymember";
    			
    			stmt = conn.createStatement();
    			
    			rs = stmt.executeQuery(sql);
    			
    			while(rs.next()) {
    				String memId =rs.getString("mem_id");
    				String memName =rs.getString("mem_name");
    				String memTel =rs.getString("mem_tel");
    				String memAddr =rs.getString("mem_addr");
    				System.out.println(memId + "\t" +memName +"\t" +memTel +"\t" + memAddr);	
    			}
    			System.out.println("--------------------------------------------------");
    			System.out.println("출력 작업 끝.");
    			
    		}catch(SQLException e) {
    			System.out.println("출력 작업 실패!!!");
    			e.printStackTrace();
    		}finally {
    			JDBCUtil.close(conn, stmt, pstmt, rs);
    		}
    		
    	}


     

    728x90
Designed by Tistory.