프로그래밍/JDBC

03 JDBC : PreparedStatement 를 사용하여 insert, update, delete 구문 수행하기

pupu91 2022. 8. 29. 16:33
반응형

 

 

1. properties 파일 생성 후 오라클 정보 작성

 

 

 

 

2. 사용할 쿼리문 작성

 

 

 

 

 

3.  diver 등록 , close메소드 작성

 

 

 

 

4. DTO 설정

 


- selet 구문 수행시에는 결과 값이 ResultSet 객체 타입으로 반환

  insert , update, delete 구문 수행시 int로 반환(삽입 / 수정 / 삭제 된 행의 개수 반환)

 

- selet 수행 시에는 executeQuery()

  insert, update, delete 수행 시에는 executeUpdate()

 

 

INSERT

	public static void main(String[] args) {
    	
        Connection conn = getConnection()
        PreparedStatement pstmt = null;
        
        int result = 0;
        
        Properties prop = new Properties();
        
        try{
        	쿼리문 불러오기
        	prop.loadFromXML(new FileInputStream("mapper/menu-query.xml")); 
            쿼리문의 키값 불러오기
            String query = prop.getProperty("inserMenu");
            
            방금 가져온 onnection안의 있는prepareStatement메소드로 query를 전달하면서 생성
            pstmt = conn.prepareStatement(query)
            
            타입에 맞게 값 채워주기
            pstmt.setString(1, "봉골레파스타");
            pstmt.seInt(2, 5000);
            pstmt.setInt(3, 4);
            pstmt.setString(4, y);
            
            실행하기
            result = pstmt.executeUpdate();
            	
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                close(pstmt);
                close(conn);
            }
            result값 확인 출력
			System.out.println("result : " + result);
        }   
    }
    
출력 결과
INTO TBL_MENU
(
  MENU_CODE
, MENU_NAME
, MENU_PRICE
, CATEGORY_CODE
, ORDERABLE_STATUS
 )  
 VALUES
(
 SEQ_MENU_CODE.NEXTVAL
, '봉공레청국장'  
, 50000
, 4
, 'Y'
		)
result : 1

 

 

 

 

 

입력받은 값으로 insert 처리 하기

public class Application2 {

	public static void main(String[] args) {
   
    - 별도의 클래스에서 입력 받는다고 가정하고 작성 -
    Scanner sc = new Scanner(System.in);
    
    System.out.println("메뉴의 이름을 입력하세요 : ");
    String menuName = sc.nextLine();
    System.out.println("메뉴의 가격을 입력하세요 : ");
	int menuPrice = sc.nextInt();
	System.out.println("카테고리 코드를 입력하세요 : ");
	int categoryCode = sc.nextInt();
	System.out.println("판매여부를 결정해주세요(Y/N) : ");
	sc.nextLine(); // 입력값 비우기
	String orderableStatus = sc.nextLine().toUpperCase(); //대문자 처리
   
    - 값을 뭉쳐서 보내기 위해 MenuDTO에 담아 전송 -
    MenuDTO newMenu = new MenuDTO();
	newMenu.setName(menuName);
	newMenu.setPrice(menuPrice);
	newMenu.setCategoryCode(categoryCode);
	newMenu.setOrderableStatus(orderableStatus);
    
    
    Connection conn = getConnection();
    PreparedStatement pstmt = null;
    int result = 0;
    
    Properties prop = new Properties();
    
    try{
    	sql 구문을 코드로 작성하지 않고 xml에 미리 작성 후 
        FileInputStream로 쿼리를 가져와서 prop에 저장
    	prop.loadFromXML(new FileInputStream("mapper/menu-query.xml"));
        String query = prop.getProperty("inserMenu");
        
        pstmt = conn.prepareStatement(query);
       
       	newMenu로부터 각각 속성 값을 가져와서 ? 위치에 삽입
        각각 속성 타입에 맞게 설정
        pstmt.setString(1, newMenu.getName());
		pstmt.setInt(2, newMenu.getPrice());
		pstmt.setInt(3, newMenu.getCategoryCode());
		pstmt.setString(4,newMenu.getOrderableStatus());   
        
        실행하기
		result = pstmt.executeUpdate();        
       
       	} catch (IOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(pstmt);
			close(conn);
		}
        
        최종결과를 리절트 결과 값이 0개행 이상이면 메뉴 등록에 성공하였습니다 출력
        if(result > 0 ) {
			System.out.println("메뉴 등록에 성공하였습니다");
		}else {
			System.out.println("메뉴 등록에 실패하였습니다");
		}
   }   
 }

 

 

UPDATE

메뉴 코드를 입력받아 해당 메뉴 코드의 내용을 입력 받은 내용으로 수정하는 코드 작성하기

1. 사용자의 입력 값을 받아서 dto로 가공하는 처리

	Scanner sc = new Scanner(System.in);
		Scanner sc = new Scanner(System.in);
		System.out.print("변경할 메뉴 번호를 입력 :");
		int menuCode = sc.nextInt();
		System.out.print("변경할 메뉴의 이름 입력 : ");
		sc.nextLine(); //수행 전에 남아있는 int 나머지 값 제거 
		String menuName = sc.nextLine();
		System.out.print("변경할 메뉴의 가격 입력 : ");
		int menuPrice = sc.nextInt();
		System.out.print("변경할 메뉴의 카테고리 번호 입력 :");
		int categoryCode = sc.nextInt();
		System.out.print("변경할 메뉴의 판매 상태 입력 : ");
		sc.nextLine();
		String orderableStatus = sc.nextLine().toUpperCase();
        
        MenuDTO changedMenu = new MenuDTO();
		changedMenu.setCode(menuCode);
		changedMenu.setName(menuName);
		changedMenu.setPrice(menuPrice);
		changedMenu.setCategoryCode(categoryCode);
		changedMenu.setOrderableStatus(orderableStatus);
-------------------------------------------------------------------------------
	
    Connection conn = getConnection();
    PreparedStatement pstmt = null;
    int result = 0;
    
    Properties prop = new Properties();
    try {
    	 
         prop.loadFromXML(new FileInputStream("mapper/menu-query.xml"));
         String query = prop.getProperty("updateMenu");
         
         pstmt = conn.prepareStatement(query);	
		 pstmt.setString(1, changedMenu.getName());
		 pstmt.setInt(2, changedMenu.getPrice());
		 pstmt.setInt(3, changedMenu.getCategoryCode());
		 pstmt.setString(4, changedMenu.getOrderableStatus());
		 pstmt.setInt(5, changedMenu.getCode());
    
    	result = pstmt.executeUpdate();
		
        } catch (IOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(pstmt);
			close(conn);
		}	
		
		if(result>0) {
			System.out.println("메뉴 변경에 성공하였습니다.");
		}else {
			System.out.println("메뉴 변경에 실패하였습니다.");
		}

 

 


DELETE

Scanner로 menuCode 값을 입력 받아 1행을 삭제하고 삭제 여부를 결과로 출력하기

Scanner sc = new Scanner(System.in);
System.out.println("삭제할 메뉴 번호를 입력하세요 : ");
int menuCode = sc.nextInt();

Connection conn = getConnection();
PreparedStatement pstmt = null;
int result = 0;

Properties prop = new Properties();
try {
		prop.loadFromXML(new FileInputStream("mapper/menu-query.xml"));
		String query = prop.getProperty("deletMenu");
			
		pstmt = conn.prepareStatement(query);
        pstmt.setInt(1, menuCode);
        
        result = pstmt.executeUpdate();
        
	} catch (IOException e) {
			e.printStackTrace();
	} catch (SQLException e) {
			e.printStackTrace();
	}finally {
			close(pstmt);
			close(conn);
	} 
		
	if(result > 0 ) {
		System.out.println("메뉴 삭제를 완료했습니다.");
	} else {
		System.out.println("메뉴 삭제를 실패했습니다.");
	}
반응형