CRUD 상품 프로그램

Soozoo·2024년 7월 11일

JAVA

목록 보기
38/41

Java JDBC를 이용한 CRUD 예제 - GiftCRUD 클래스 분석과 설명

이 Java 프로그램은 JDBC를 사용하여 Oracle 데이터베이스에서 Gift 테이블의 데이터를 관리하는 CRUD 기능을 제공합니다. 각 메소드는 데이터베이스 연결을 통해 쿼리를 실행하고, 사용자 입력을 통해 데이터를 조회, 추가, 수정, 삭제할 수 있습니다.

1. connect() 메소드

데이터베이스에 연결하는 메소드입니다. 사용자로부터 ID와 비밀번호를 입력받아 Oracle JDBC 드라이버를 로드하고, Connection 객체를 생성합니다.

public void connect() throws ClassNotFoundException, SQLException {
    Scanner sc = new Scanner(System.in);

    // 1. Driver load
    Class.forName("oracle.jdbc.OracleDriver");
    System.out.println("driver load success!!!");

    // 2. Connection & Open
    String url = "jdbc:oracle:thin:@192.168.0.143:1521:xe";
    System.out.print("사용자 ID 입력: ");
    String uid = sc.next();
    System.out.print("비밀번호 입력: ");
    String pwd = sc.next();

    conn = DriverManager.getConnection(url, uid, pwd);
    System.out.println("connection success!!!");
}

2. selectAll() 메소드

Gift 테이블의 모든 데이터를 조회하여 출력하는 메소드입니다. Statement를 사용하여 실행합니다.

public void selectAll() throws ClassNotFoundException, SQLException {
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM GIFT");

    System.out.println("상품번호\\t상품명\\t최저가\\t최고가");
    System.out.println("----------------------------------------------");
    while (rs.next()) {
        int gno = rs.getInt(1);
        String gname = rs.getString("gname");
        int g_s = rs.getInt(3);
        int g_e = rs.getInt("g_end");

        System.out.println(gno + "\\t" + gname + "\\t" + g_s + "\\t" + g_e);
    }

    rs.close();
    stmt.close();
}

3. select() 메소드

사용자로부터 입력받은 상품번호에 해당하는 데이터를 조회하는 메소드입니다. PreparedStatement를 사용하여 SQL Injection 공격을 방지합니다.

public void select() {
    try {
        Scanner sc = new Scanner(System.in);

        System.out.println("원하시는 상품의 번호를 입력하세요.");
        int gno = sc.nextInt();

        String sql = "SELECT * FROM GIFT WHERE gno = ?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, gno);

        ResultSet rs = pstmt.executeQuery();

        System.out.println("상품번호\\t상품명\\t최저가\\t최고가");
        while (rs.next()) {
            int gnoResult = rs.getInt(1);
            String gname = rs.getString("gname");
            int g_s = rs.getInt(3);
            int g_e = rs.getInt("g_end");

            System.out.println(gnoResult + "\\t" + gname + "\\t" + g_s + "\\t" + g_e);
        }

        rs.close();
        pstmt.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

4. insert() 메소드

새로운 상품 데이터를 입력하는 메소드입니다. 사용자로부터 상품번호, 상품명, 최저가, 최고가를 입력받아 PreparedStatement를 사용하여 데이터베이스에 삽입합니다.

public void insert() {
    try {
        Scanner sc = new Scanner(System.in);

        System.out.print("상품번호 입력: ");
        int productId = sc.nextInt();
        System.out.print("상품명 입력: ");
        String productName = sc.next();
        System.out.print("최저가 입력: ");
        int minPrice = sc.nextInt();
        System.out.print("최고가 입력: ");
        int maxPrice = sc.nextInt();

        String sql = "INSERT INTO GIFT VALUES(?,?,?,?)";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, productId);
        pstmt.setString(2, productName);
        pstmt.setInt(3, minPrice);
        pstmt.setInt(4, maxPrice);

        int result = pstmt.executeUpdate();
        System.out.println(result + "개 데이터 추가 성공!!");

        pstmt.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

5. Update() 메소드

상품 데이터를 수정하는 메소드입니다. 사용자로부터 변경할 상품번호, 상품명, 최저가, 최고가를 입력받아 PreparedStatement를 사용하여 데이터를 업데이트합니다.

public void Update() {
    Scanner sc = new Scanner(System.in);

    try {
        System.out.println("Gift table update");

        System.out.print("변경할 번호를 입력하세요 :");
        int gno = sc.nextInt();

        sc.nextLine(); // 버퍼 비우기

        System.out.print("변경할 물품의 이름을 입력하세요. ");
        String gname = sc.nextLine();

        System.out.print("변경할 시작금액을 입력하세요: ");
        int g_start = sc.nextInt();

        System.out.print("변경할 최고금액을 입력하세요: ");
        int g_end = sc.nextInt();

        String sql = "UPDATE Gift SET gname = ?, g_start = ?, g_end = ? WHERE gno = ?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, gname);   // gname
        pstmt.setInt(2, g_start);    // g_start
        pstmt.setInt(3, g_end);      // g_end
        pstmt.setInt(4, gno);

        int result = pstmt.executeUpdate();
        System.out.println(result + "개 데이터 수정 성공!!");

        pstmt.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

6. Delete() 메소드

상품 데이터를 삭제하는 메소드입니다. 사용자로부터 삭제할 상품번호를 입력받아 PreparedStatement를 사용하여 해당 데이터를 삭제합니다.

public void Delete() {
    Scanner sc = new Scanner(System.in);

    try {
        System.out.println("Gift table update");

        System.out.print("삭제할 번호를 입력하세요 :");
        int gno = sc.nextInt();

        String sql = "DELETE FROM Gift WHERE gno = ?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, gno);

        int result = pstmt.executeUpdate();
        System.out.println(result + "개 데이터 삭제 성공!!");

        pstmt.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

7. End() 메소드

프로그램을 종료하는 메소드입니다. System.exit(0)을 호출하여 프로그램을 종료합니다.

8. Menu() 메소드

사용자에게 메뉴를 보여주는 메소드입니다. 각 기능에 해당하는 번호를 입력받아 CRUD 기능을 선택할 수 있습니다.

9. main() 메소드

프로그램의 진입점입니다. GiftCRUD 객체를 생성하고 connect() 메소드를 호출하여 데이터베이스에 연결한 후, 사용자에게 메뉴를 보여주고 선택된 기능을 수행합니다.

이 예제는 JDBC를 사용하여 Oracle 데이터베이스의 CRUD 작업을 수행하는 방법을 보여주며, PreparedStatement를 통해 SQL Injection 공격을 방지하는 방법도 함께 알려줍니다.

전체코드

package ex02.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;


public class GiftCRUD {
	
	 private Connection conn;
//	연결메소드
	  public void connect() throws ClassNotFoundException, SQLException {
	        Scanner sc = new Scanner(System.in);
	        
	        // 1. Driver load
	        Class.forName("oracle.jdbc.OracleDriver");
	        System.out.println("driver load success!!!");
	        
	        // 2. Connection & Open
	        String url = "jdbc:oracle:thin:@192.168.0.143:1521:xe";
	        System.out.print("사용자 ID 입력: ");
	        String uid = sc.next();
	        System.out.print("비밀번호 입력: ");
	        String pwd = sc.next();
	        
	        conn = DriverManager.getConnection(url, uid, pwd);
	        System.out.println("connection success!!!");
	    }
	
	
//	selectAll()
	public void selectAll() throws ClassNotFoundException, SQLException {
		Statement stmt = conn.createStatement();
		ResultSet rs =stmt.executeQuery("SELECT * FROM GIFT"); //ctrl+shift+x
		
		 System.out.println("상품번호\t상품명\t최저가\t최고가");
         System.out.println("----------------------------------------------");
		while(rs.next()) {
			int gno = rs.getInt(1); // 인덱스번호, int gno = rs.getInt("gno");
			String gname = rs.getString("gname");
			int g_s = rs.getInt(3);
			int g_e = rs.getInt("g_end");
			
			 System.out.println(gno+"\t"+gname+"\t"+ g_s+"\t"+g_e);
		} //while end
	   } //selectAll end
	
	
//	select()
	public void select() {
        try {
            
            Scanner sc = new  Scanner(System.in);
            
            System.out.println("원하시는 상품의 번호를 입력하세요.");
            int gno = sc.nextInt();
            String sql = "SELECT * FROM GIFT WHERE gno = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, gno);
            
            ResultSet rs = pstmt.executeQuery();
            
            System.out.println("상품번호\t상품명\t최저가\t최고가");
            while (rs.next()) {
                int gnoResult = rs.getInt(1);
                String gname = rs.getString("gname");
                int g_s = rs.getInt(3);
                int g_e = rs.getInt("g_end");
                
                System.out.println(gnoResult + "\t" + gname + "\t" + g_s + "\t" + g_e);
            }
            
            // 자원 반환
            rs.close();
            pstmt.close();
            conn.close();
            
        } catch (SQLException e) {
            e.printStackTrace();
        }
    } //select end
	
//	insert
	public void insert() {
		Scanner sc = new Scanner(System.in);
		
		 try {
	            
	            Scanner sc1 = new Scanner(System.in);
	            
	            System.out.print("상품번호 입력: ");
	            int productId = sc1.nextInt();
	            System.out.print("상품명 입력: ");
	            String productName = sc1.next();
	            System.out.print("최저가 입력: ");
	            int minPrice = sc1.nextInt();
	            System.out.print("최고가 입력: ");
	            int maxPrice = sc1.nextInt();
	            
	            String sql = "INSERT INTO GIFT VALUES(?,?,?,?)";
	            PreparedStatement pstmt = conn.prepareStatement(sql);
	            pstmt.setInt(1, productId);
	            pstmt.setString(2, productName);
	            pstmt.setInt(3, minPrice);
	            pstmt.setInt(4, maxPrice);
	            
	            int result = pstmt.executeUpdate(); // 데이터 삽입 실행
	            
	            System.out.println(result + "개 데이터 추가 성공!!");
	            
	            // 자원 반환
	            pstmt.close();
	            conn.close();
	            
	        } catch (SQLException e) {
	            e.printStackTrace();
	        }
	    }//insert end
	
//	update
public void Update() {
	Scanner sc =new Scanner(System.in);
	
	try {
	
	System.out.println("Gift table update");

    System.out.print("변경할 번호를 입력하세요 :");
    int gno = sc.nextInt();
    
    sc.nextLine(); // 버퍼 비우기
    
    System.out.print("변경할 물품의 이름을 입력하세요. ");
    String gname = sc.nextLine();
    
    System.out.print("변경할 시작금액을 입력하세요: ");
    int g_start = sc.nextInt();
    
    System.out.print("변경할 최고금액을 입력하세요: ");
    int g_end = sc.nextInt();
    
    String sql = "UPDATE Gift SET gname = ?, g_start = ?, g_end = ? WHERE gno = ?";
    PreparedStatement pstmt = conn.prepareStatement(sql);
    pstmt.setString(1, gname);   // gname
    pstmt.setInt(2, g_start);    // g_start
    pstmt.setInt(3, g_end);      // g_end
    pstmt.setInt(4, gno); 
    
    int result = pstmt.executeUpdate(); 
    System.out.println(result + "개 데이터 수정 성공!!");
    
    // 4. 닫기 (자원 반환)
    pstmt.close();
    conn.close();
    sc.close();
    }catch ( SQLException e) {
        e.printStackTrace();
    }
} // update end
	
//	delete

public void Delete() {
	Scanner sc = new Scanner(System.in);
	
	try {
		
		System.out.println("Gift table update");
		
	    System.out.print("삭제할 번호를 입력하세요 :");
	    int gno = sc.nextInt();
	    
	    String sql = "DELETE FROM Gift WHERE gno = ?";
	    PreparedStatement pstmt = conn.prepareStatement(sql);
	    pstmt.setInt(1, gno); 
	    
	    int result = pstmt.executeUpdate(); 
	    System.out.println(result + "개 데이터 수정 성공!!");
	    pstmt.close();
	    }catch ( SQLException e) {
	        e.printStackTrace();
	    }
	} 

	
//	end
	public void End() {
		System.out.println("시스템 종료 되었습니다.");
		System.exit(0);
	}
//	menu
	public void Menu() {
		System.out.println("1.전체물품보기 2.지정물품보기 3.물품넣기 4.물품업데이트 5.물품삭제 6.시스템종료");
	}
	
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		GiftCRUD gc = new GiftCRUD();
		Scanner sc = new Scanner(System.in);
		gc.connect();
		while(true) {
			gc.Menu();
			System.out.println("메뉴 선택: ");
			int num  = sc.nextInt();
			switch(num){
				
				case 1: gc.selectAll();
				break;
				case 2: gc.select();
				break;
				case 3: gc.insert();
				break;
				case 4: gc.Update();	
				break;
				case 5: gc.Delete();
				break;
				case 6: gc.End();
				break;
				default : System.out.println("잘못된 입력 다시 입력!!");
			}//end switch
		}//end while
	}//end main
}
profile
넙-죽

0개의 댓글