도서 관리 프로그램

package jdbctest3;

import java.sql.*;
import java.util.*;

public class BookList {
	
	Connection conn; //맴버변수로 만들어준 이유 ? try문으로 감싸기 때문에 지역변수가 되는데 그것을 방지하기 위함
	
	public BookList() { // 생성자 선언 --> 이유는? main에서 BookList 객체 생성하면 이 생성자 선언 영역으로 와서 dbConnect()를 호출 
		dbConnect();
	}
	
	/** DB연동 관련 메서드 */
	public void dbConnect() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			String url = "jdbc:oracle:thin:@localhost:1521:xe";
			String user = "scott";
			String pwd = "1234";
		    conn = DriverManager.getConnection(url, user, pwd);
		}catch(ClassNotFoundException e) {
			System.out.println("DB 드라이버 경로 잘못됨~");
		}catch(SQLException e) {
			System.out.println("url 및 계정 또는 비밀번호가 잘못되었습니다.");
		}
	}
	
	/** 메뉴 관련 메서드 */
	public int printMenu(Scanner sc) {
		System.out.println("======================");
		System.out.println("도서관리 프로그램v1.0");
		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("메뉴>>");
		int menu = sc.nextInt();
		sc.nextLine();
		return menu;
	}

	/** 1. 도서 등록 관련 메서드 */
	public void registerBook(Scanner sc) {
		System.out.println("==도서 등록==");
		System.out.print("책 제목:");
		String book = sc.nextLine();
		System.out.print("저자 이름:");
		String name = sc.nextLine();
		System.out.print("가격:");
		String price = sc.nextLine();
		System.out.print("분야:");
		String field = sc.nextLine();
		
		try {
			String sql="insert into booklist values(booklist_idx2.nextval,?,?,?,?)";
			PreparedStatement ps = conn.prepareStatement(sql); // 4개의 좌석을 가진 버스를 생성
			// 4개의 좌석에 사람을 앉힘
			ps.setString(1, book);
			ps.setString(2, name);
			ps.setString(3, price);
			ps.setString(4, field);
			int count = ps.executeUpdate();// 버스 출발 
			System.out.println(count+"개의 도서정보가 등록 되었습니다.");
			
			ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	/** 2. 도서 정보 리스트 관련 메서드 */
	public void bookList() {
		System.out.println("==등록된 도서 목록==");

		try {
			String sql = "select * from booklist";
			PreparedStatement ps = conn.prepareStatement(sql); // 버스를 만듬
			ResultSet rs = ps.executeQuery(); // SQL문이 SELECT이면 열거형클래스인 ResultSet를 이용해서 자바프로그램에서 반환해줘야함. 그리고 쿼리를 추출

			System.out.println("---------------------------------------------------------------------");
			System.out.println("도서번호\\t제목\\t\\t\\t저자\\t\\t가격\\t\\t분야");
			System.out.println("---------------------------------------------------------------------");
			if (rs.next()) {
				do {
					int idx = rs.getInt("idx");
					String book = rs.getString("book");
					String name = rs.getString("name");
					String price = rs.getString("price");
					String field = rs.getString("field");
					System.out.println(idx + "\\t\\t\\t" + book + "\\t\\t" + name + "\\t" + price + "\\t" + field);
					System.out.println("---------------------------------------------------------------------");

				} while (rs.next());
			} else {
				System.out.println("등록된 책이 없습니다.");
			}
			rs.close();
			ps.close();
		}  catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/** 3. 도서 검색 관련 메서드 */
	public void searchBook(Scanner sc) {
		try {
			System.out.println("==도서 검색==");
			System.out.println("검색 방법 >> 1. 책제목, 2.저자이름");
			System.out.print("선택:");
			int select = sc.nextInt();
			sc.nextLine();
			
			if(select==1) {
				System.out.print("책 제목:");
				String book = sc.nextLine();
				String sql = "select * from booklist where book=?";
				PreparedStatement ps = conn.prepareStatement(sql);
				ps.setString(1, book);
				
				ResultSet rs = ps.executeQuery();
				System.out.println("도서번호\\t제목\\t저자\\t가격\\t분야");
				if(rs.next()) {
					do {
						int idx = rs.getInt("idx");
						String dbbook = rs.getString("book");
						String name = rs.getString("name");
						String price = rs.getString("price");
						String field = rs.getString("field");
						
						System.out.println(idx+"\\t"+dbbook+"\\t"+name+"\\t"+price+"\\t"+field);
					}while(rs.next());
				}else {
					System.out.println(book+"의 도서 정보가 없습니다.");
				}
				rs.close();
				ps.close();
			}else if(select==2) {
				System.out.print("저자 이름:");
				String name=sc.nextLine();
				String sql = "select * from booklist where name=?";
				PreparedStatement ps = conn.prepareStatement(sql);
				ps.setString(1, name);
				ResultSet rs= ps.executeQuery();
				System.out.println("도서번호\\t제목\\t저자\\t가격\\t\\t분야");
				if(rs.next()) {
					do {
						int idx = rs.getInt("idx");
						String dbbook = rs.getString("book");
						String dbname = rs.getString("name");
						String price = rs.getString("price");
						String field = rs.getString("field");
						
						System.out.println(idx+"\\t\\t\\t"+dbbook+"\\t"+dbname+"\\t"+price+"\\t"+field);
					}while(rs.next());
				}else {
					System.out.println(name+"님과 관련된 도서 정보가 없습니다.");
				}
				rs.close();
				ps.close();
			}
		}  catch (SQLException e) {
			e.printStackTrace();
		}
		
		
	}

	/** 4. 도서 수정 관련 메서드 */
	public void updateBook(Scanner sc) {
		System.out.println("==도서 수정==");

		System.out.print("책 번호 입력:");
		int idx = sc.nextInt();
		sc.nextLine();
		System.out.println("--수정 시작--");
		System.out.print("책 제목:");
		String book = sc.nextLine();
		System.out.print("저자 이름:");
		String name = sc.nextLine();
		System.out.print("가격:");
		String price = sc.nextLine();
		System.out.print("분야:");
		String field = sc.nextLine();

		try {
			String sql = "update booklist set book=?, name=?, price=?, field=? where idx=?";
			PreparedStatement ps = conn.prepareStatement(sql);

			ps.setString(1, book);
			ps.setString(2, name);
			ps.setString(3, price);
			ps.setString(4, field);
			ps.setInt(5, idx);
			int count = ps.executeUpdate();

			System.out.println(count + "개의 도서가 수정 되었습니다.");
			ps.close();
		}  catch (SQLException e) {
			e.printStackTrace();
		}

	}

	/** 종료 기능 관련 메서드*/  // case 5에 해당하는 종료 기능을 메서드로 만들어 사용하는 이유 : conn에 대한 자원회수를 하기위해
	public void programExit() { 
		try {
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println("프로그램을 종료합니다.");
		System.exit(0);
	}
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		BookList bl = new BookList();
		while (true) {
			int menu = bl.printMenu(sc);

			switch (menu) {
			case 1:bl.registerBook(sc); break;
			case 2:bl.bookList(); break;
			case 3:bl.searchBook(sc); break;
			case 4:bl.updateBook(sc); break;
			case 5:bl.programExit(); break;
			}

		}
	}

}