고급JAVA 18강 - JDBC

Whatever·2021년 11월 22일
0

고급 JAVA

목록 보기
18/32

JDBC 예제

package kr.or.ddit.basic;

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.DBUtil;
// MVC 패턴 -- 조사해서 레포트로 제출


/*
	회원을 관리하는 프로그램을 작성하시오.
	(MYMEMBER 테이블 이용)

	아래 메뉴의 기능을 모두 구현하시오. (CRUD기능 구현하기)
	메뉴 예시)
		== 작업 선택 ==
		1. 자료 추가 
		2. 자료 삭제
		3. 자료 수정
		4. 전체 자료 출력
		0. 작업 끝.
	
	처리조건)
	1) 자료 추가에서 '회원ID'는 중복되지 않는다.(중복되면 다시 입력 받는다.)
	2) 삭제는 '회원ID'를 입력 받아서 처리한다.
	3) 자료 수정에서 '회원ID'는 변경되지 않는다.
		

*/
public class JdbcTest06 {
	private Scanner scan = new Scanner(System.in);
	
	
	public static void main(String[] args) {
		new JdbcTest06().memberStart();
	}
	
	public void memberStart(){
		while(true){
			int choice = displayMenu();
			switch(choice){
				case 1 :	// 추가 
					insertMember(); break;
				case 2 : 	// 삭제
					deleteMember(); break;
				case 3 : 	// 수정  ==> 전체 항목 수정
					updateMember(); break;
				case 4 : 	// 전체 자료 출력
					displayMember(); break;
				case 5 : 	// 수정	==> 원하는 항목만 수정
					updateMember2(); break;
				case 0 : 	// 종료
					System.out.println("작업을 마칩니다.");
					return;
				default : 
					System.out.println("번호를 잘못 입력했습니다. 다시입력하세요.");
			}
		}
	}
	
	// 회원 정보를 추가하는 메서드
	private void insertMember(){
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		System.out.println();
		System.out.println("추가할 회원 정보를 입력하세요.");
		
		int count = 0;
		String memId = null;  // 회원ID가 저장될 변수
		do{
			System.out.print("회원ID >> ");
			memId = scan.next();
			count = getMemberCount(memId);
			if(count>0){
				System.out.println(memId + "은(는) 이미 등록된 회원ID입니다.");
				System.out.println("다른 회원ID를 입력하세요.");
			}
			
		}while(count>0);
		
		System.out.print("회원이름 >> ");
		String memName = scan.next();
		
		System.out.print("비밀번호 >> ");
		String memPass = scan.next();
		
		System.out.print("전화번호 >> ");
		String memTel = scan.next();
		
		scan.nextLine();  // 입력 버퍼 비우기
		System.out.print("회원주소 >> ");
		String memAddr = scan.nextLine();
		
		try {
			conn = DBUtil.getConnection();
			
			String sql = "insert into mymember "
					+ "(mem_id, mem_name, mem_pass, mem_tel, mem_addr) "
					+ "values(?, ?, ?, ?, ?) ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, memId);
			pstmt.setString(2, memName);
			pstmt.setString(3, memPass);
			pstmt.setString(4, memTel);
			pstmt.setString(5, memAddr);
			
			int cnt = pstmt.executeUpdate();
			if( cnt>0 ){
				System.out.println("회원 정보 추가 성공!!!");
			}else{
				System.out.println("회원 정보 추가 실패~~~");
			}
			
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if(pstmt!=null) try{ pstmt.close();   }catch(SQLException e){}
			if(conn!=null) try{ conn.close();   }catch(SQLException e){}
		}
		
	}
	
	// 회원 정보를 삭제하는 메서드
	private void deleteMember(){
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		System.out.println();
		System.out.println("삭제할 회원 정보를 입력하세요.");
		System.out.print("삭제할 회원ID >> ");
		String memId = scan.next();
		
		try {
			conn = DBUtil.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("회원ID가 " + memId + "인 회원 삭제 성공!!");
			}else{
				System.out.println(memId + "은(는) 없는 회원ID이거나 "
						+ "삭제에 실패했습니다.");
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if(pstmt!=null) try{ pstmt.close();   }catch(SQLException e){}
			if(conn!=null) try{ conn.close();   }catch(SQLException e){}
		}
	}
	
	// 회원 정보를 수정하는 메서드  ==> 전체 항목 수정
	private void updateMember(){
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		System.out.println();
		System.out.println("수정할 회원 정보를 입력하세요.");
		System.out.print("수정할 회원ID >> ");
		String memId = scan.next();
		
		int count = getMemberCount(memId);
		if(count==0){ // 없는 회원이면...
			System.out.println(memId + "은(는) 없는 회원ID입니다.");
			System.out.println("수정 작업을 중단합니다.");
			return;
		}
		
		System.out.println();
		System.out.println("수정할 내용을 입력하세요.");
		System.out.print("새로운 회원이름 >> ");
		String newMemName = scan.next();
		
		System.out.print("새로운 비밀번호 >> ");
		String newMemPass = scan.next();
		
		System.out.print("새로운 전화번호 >> ");
		String newMemTel = scan.next();
		
		scan.nextLine();
		System.out.print("새로운 회원주소 >> ");
		String newMemAddr = scan.nextLine();
		
		try {
			conn = DBUtil.getConnection();
			
			String sql = "update mymember "
					+ " set mem_name = ?, mem_pass = ?, mem_tel = ?, mem_addr = ? "
					+ " where mem_id = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, newMemName);
			pstmt.setString(2, newMemPass);
			pstmt.setString(3, newMemTel);
			pstmt.setString(4, newMemAddr);
			pstmt.setString(5, memId);
			
			int cnt = pstmt.executeUpdate();
			
			if(cnt>0){
				System.out.println(memId + "회원 정보 수정 완료!!!");
			}else{
				System.out.println(memId + "회원 정보 수정 실패~~~");
			}
			
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			if(pstmt!=null) try{ pstmt.close();   }catch(SQLException e){}
			if(conn!=null) try{ conn.close();   }catch(SQLException e){}
		}
		
	}
	
	// 회원 정보를 수정하는 메서드  ==> 원하는 항목 수정 
	private void updateMember2(){
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		System.out.println();
		System.out.println("수정할 회원 정보를 입력하세요.");
		System.out.print("수정할 회원ID >> ");
		String memId = scan.next();
		
		int count = getMemberCount(memId);
		if(count==0){ // 없는 회원이면...
			System.out.println(memId + "은(는) 없는 회원ID입니다.");
			System.out.println("수정 작업을 중단합니다.");
			return;
		}
		
		int num; // 수정할 컬럼에 대한 선택 값이 저장될 변수
		String updateField = null;
		String updateTitle = null;
		do{
			System.out.println();
			System.out.println("수정할 항목을 선택하세요.");
			System.out.println(" 1.회원이름  2.비밀번호  3.전화번호  4.회원주소");
			System.out.println("----------------------------------------------");
			System.out.print("수정할 항목 선택 >> ");
			num = scan.nextInt();
			
			switch(num){
				case 1 : updateField = "mem_name";
						 updateTitle = "회원이름"; break;
				case 2 : updateField = "mem_pass";
						 updateTitle = "비밀번호"; break;
				case 3 : updateField = "mem_tel";
						 updateTitle = "전화번호"; break;
				case 4 : updateField = "mem_addr";
						 updateTitle = "회원주소"; break;
				default : 
					System.out.println("수정할 항목을 잘못 선택했습니다.");
					System.out.println("다시 선택하세요.");
			}
		}while(num<1 || num>4);
		
		scan.nextLine();  // 입력 버퍼 비우기
		System.out.println();
		System.out.print("새로운 " + updateTitle + " >> ");
		String updateData = scan.nextLine();
		
		try {
			conn = DBUtil.getConnection();
			
			// update mymember set 수정할컬럼명 = 수정할값 where mem_id=수정할회원ID
			String sql = "update mymember "
					+ " set " + updateField + " = ? "
					+ " where mem_id = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, updateData);
			pstmt.setString(2, memId);

			int cnt = pstmt.executeUpdate();
			
			if(cnt>0){
				System.out.println(memId + " 회원 정보 수정 완료!!!");
			}else{
				System.out.println(memId + " 회원 정보 수정 실패~~~");
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if(pstmt!=null) try{ pstmt.close();   }catch(SQLException e){}
			if(conn!=null) try{ conn.close();   }catch(SQLException e){}
		}
		
	}
	
	
	// 전체 회원 정보를 출력하는 메서드
	private void displayMember(){
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		
		System.out.println();
		System.out.println("===============================================");
		System.out.println(" 회원ID   회원이름  비밀번호   전화번호    주 소");
		System.out.println("===============================================");
		
		try {
			conn = DBUtil.getConnection();
			
			String sql = "select * from mymember";
			stmt = conn.createStatement();
			
			rs = stmt.executeQuery(sql);
			
			while(rs.next()){
				System.out.print(rs.getString("mem_id") + "\t");
				System.out.print(rs.getString("mem_name") + "\t");
				System.out.print(rs.getString("mem_pass") + "\t");
				System.out.print(rs.getString("mem_tel") + "\t");
				System.out.println(rs.getString("mem_addr"));
			}
			System.out.println("===============================================");
			System.out.println("출력 작업 끝...");
			
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if(rs!=null) try{ rs.close();   }catch(SQLException e){}
			if(stmt!=null) try{ stmt.close();   }catch(SQLException e){}
			if(conn!=null) try{ conn.close();   }catch(SQLException e){}
		}
		
	}
	
	// 회원ID를 인수값으로 받아서 해당 회원ID의 개수를 반환하는 메서드
	private int getMemberCount(String memId){
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		int count = 0;
		try {
			conn = DBUtil.getConnection();
			
			String sql = "select count(*) cnt from mymember where mem_id = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, memId);
			
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				count = rs.getInt("cnt");
			}
			
		} catch (SQLException e) {
			count = 0;
			e.printStackTrace();
		} finally {
			if(rs!=null) try{ rs.close();   }catch(SQLException e){}
			if(pstmt!=null) try{ pstmt.close();   }catch(SQLException e){}
			if(conn!=null) try{ conn.close();   }catch(SQLException e){}
		}
		
		return count;
		
	}
	
	// 메뉴를 출력하고 선택한 작업 번호를 반환하는 메서드
	private int displayMenu(){
		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. 자료 수정2");
		System.out.println("0. 작업 끝.");
		System.out.println("==================");
		System.out.print("원하는 작업 선택 >> ");
		int num = scan.nextInt();
		return num;
	}
	
	
	
	
	
	

}

Properties 작성

새로만들기> source folder만들기> Untitled Text file만들기> 작성

# 이 줄은 주석 처리 줄 입니다.
# 이 properties문서를 작성하는 방법
# key값=value값과 같이 작성한다.

driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
user=JYJ94
pass=java

driver, url, user, pass에 값을 부여한다.

읽어오기
방법 1) Properties 객체 이용
방법 2) ResourceBundle 객체 이용

=> ResourceBundle객체 이용을 많이 함 - 코드가 단순해서

PropertiesTest

public class PropertiesTest {

	public static void main(String[] args) {
		// 읽어온 정보를 저장할 Properties객체 생성
		Properties prop = new Properties();
		
		// 읽어올 파일명을 이용한 File객체 생성
		File f = new File("res/kr/or/ddit/config/dbinfo.properties");
		FileInputStream fin = null;
		try {
			// 파일 내용을 읽어올 입력용 스트림 객체 생성
			fin = new FileInputStream(f);
			
			// 입력용 스트림 객체를 이용하여 파일 내용을 읽어와 Properties객체에 저장하기
			// 파일 내용을 읽어와 'key값'과 'value값'을 분류한 후 그 내용을 Properties객체에 저장한다.
			prop.load(fin);
			
			// 읽어온 정보를 출력해보기
			System.out.println("driver : " + prop.getProperty("driver"));
			System.out.println("url : " + prop.getProperty("url"));
			System.out.println("user : " + prop.getProperty("user"));
			System.out.println("pass : " + prop.getProperty("pass"));
			
			
		} catch (IOException e) {
			System.out.println("입출력 오류입니다.");
			e.printStackTrace();
		}finally {
			if(fin!=null)try {fin.close();} catch(IOException e) {}
		}
	}

}

ResourceBundle객체

/*
	ResourceBundle객체 
	==> 파일의 확장자가 properties인 파일의 내용을 읽어와 key값과 value값을 분리해서 정보를 갖고 있는 객체
	
	==> 읽어올 파일의 내용은 'key값=value값' 형태로 되어 있어야 한다.
	
*/

public class ResourceBundleTest {

	public static void main(String[] args) {
		// ResourceBundle객체를 이용하여 파일 읽어오기
		
		// ResourceBundle객체 생성하기
		// ==> 읽어올 파일을 지정할 때 '패키지명.파일명'까지만 지정하고 확장자는 기술하지 않는다.
		
		ResourceBundle bundle = ResourceBundle.getBundle("kr.or.ddit.config.dbinfo");

		// 읽어온 내용 출력하기
		System.out.println("driver : " + bundle.getString("driver"));
		System.out.println("url : " + bundle.getString("url"));
		System.out.println("user : " + bundle.getString("user"));
		System.out.println("pass : " + bundle.getString("pass"));
	}

}

JDBC1 - properties객체 이용

// JDBC 드라이버를 로딩하고 Connection객체를 생성하는 메서드로 구성된 class 만들기
// (dbinfo.properties파일의 내용으로 설정하는 방법)

// 방법1 : properties객체 이용하기

public class DBUtil2 {
	private static Properties prop; // Properties객체 변수 선언 - static으로 선언
          (static 메서드 안에서 사용하기 위해)
	// static 초기화 블럭 
	static {
		prop = new Properties(); //Properties객체 생성
		File f = new File("res/kr/or/ddit/config/dbinfo.properties");
		FileInputStream fin = null;
		
		try {
			fin = new FileInputStream(f); // 입력 스트림 객체 생
			prop.load(fin);
			
			//Class.forName("oracle.jdbc.driver.OracleDriver");
			Class.forName(prop.getProperty("driver"));
			
		} catch (ClassNotFoundException e) {
			System.out.println("드라이버 로딩 실패~~~");
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			System.out.println("설정 파일이 없습니다.");
			System.out.println("드라이버 로딩 실패~~~");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("입출력 오류");
			System.out.println("드라이버 로딩 실패~~~");
			e.printStackTrace();
		}finally {
			if(fin!=null)try {fin.close();}catch(IOException e) {}
		}
		
	}
	
	public static Connection getConnection() {
		try {
			//return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
            "JYJ94", "java");
			return DriverManager.getConnection(
					prop.getProperty("url"), 
					prop.getProperty("user"), 
					prop.getProperty("pass"));
			
		} catch (SQLException e) {
			System.out.println("오라클 연결 실패!!!");
			return null;
		}
	}

}

JDBC2 - ResourceBundle객체 이용

// JDBC 드라이버를 로딩하고 Connection객체를 생성하는 메서드로 구성된 class 만들기
//( dbinfo.properties파일의 내용으로 설정하는 방법)

// 방법2 : ResourceBundle객체 이용하기

public class DBUtil3 {
	private static ResourceBundle bundle; // ResourceBundle객체 변수 선언
	
	// static 초기화 블럭 - 왜 초기화블럭에서 실행할까?
	static {
		bundle = ResourceBundle.getBundle("kr.or.ddit.config.dbinfo");
		
		try {
			Class.forName(bundle.getString("driver"));
			//Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			System.out.println("드라이버 로딩 실패~~~");
			e.printStackTrace();
		}
		
	}
	
	public static Connection getConnection() {
		try {
			//return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
            "JYJ94", "java");
			return DriverManager.getConnection(
					bundle.getString("url"), 
					bundle.getString("user"), 
					bundle.getString("pass"));
		} catch (SQLException e) {
			System.out.println("오라클 연결 실패!!!");
			return null;
		}
	}

}

0개의 댓글