디지털 컨버전스/JDBC

[JDBC] OJDBC, forName, Connection, Statement, executeUpdate, executeQuery

gimyeondong 2020. 3. 24. 09:08

//매서드와 arrayList 복습


  • DB <-> Java
  • 소켓 통신
  • 오라클의 프로토콜을 알아야함
  • 우리가 아는 데이터 inputstream 등등과는 다른 기능
  • 우리가 모르는 기능 -> 라이브러리 활용
  • 통신 라이브러리 파일 : OJDBC (Oracle Java Database Connection)
  • 자바의 표준이 아님 : 내장/시스템 라이브러리가 아님
  • 오라클XE에 포함되어 있음 (C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6)

 

 

 


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

//매서드와 arrayList 복습
// DB <-> Java
// 소켓 통신
// 오라클의 프로토콜을 알아야함
// 우리가 아는 데이터 inputstream 등등과는 다른 기능
// 우리가 모르는 기능 -> 라이브러리 활용
// 통신 라이브러리 파일 : OJDBC (Oracle Java Database Connection)
// 자바의 표준이 아님 : 내장/시스템 라이브러리가 아님
// 오라클XE에 포함되어 있음 (C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6)

public class Exam_01 {
	public static void main(String[] args) {
		//인스턴스 new 대신 리플렉션이라는 기법 사용	

		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			//패키지명.매서드오라클드라이버
			//프레임워크 + 어떤데이터베이스를 쓸지 결정
			// DBMS driver loading code
			// 라이브러리를 추가 안하면 패키지도 없고 에러
		}catch(Exception e) {
			System.out.println("드라이버 클래스를 찾을 수 없습니다!! 라이브러리 확인하세요!");
			e.printStackTrace();
			System.exit(0);
		}
		String url = "jdbc:oracle:thin:@localhost:1521:xe"; 
        //thin(연결드라이버):ip주소: :xe(파일이름)
		String loginId = "kh";
		String loginPw = "kh";

		try {

			Connection con = DriverManager.getConnection(url, loginId, loginPw);
			// new는 디자인 패턴상 좋은 기법 아님

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

Class.forName("oracle.jdbc.driver.OracleDriver"); 

// DBMS driver loading code

 


stat.executeQuery(sql);
// resultset 리턴
// SQL : select
// DBMS 변화없이 데이터보여줌


stat.executeUpdate(sql);
// int 리턴
// SQL : delect / update / insert
// 몇개의 행에 변화가 생겼다


cafe 테이블에 Espresso 추가

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;


public class Exam_01 {
	public static void main(String[] args) {


		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");

		}catch(Exception e) {
			System.out.println("드라이버 클래스를 찾을 수 없습니다!! 라이브러리 확인하세요!");
			e.printStackTrace();
			System.exit(0);;
		}
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String loginId = "kh";
		String loginPw = "kh";

		try {

		
			Connection con = DriverManager.getConnection(url, loginId, loginPw);

			Statement stat = con.createStatement();

	
			String sql = 
					"insert into cafe values(cafe_seq.nextval,'Espresso',1500)";
			// SQL 문법 대로 넣기, 단 세미콜론은 오류가 나므로 넣지 말것
			// 만약 실패했다면? 오라클 예외발생 / 성공한다면 1 
			int result = stat.executeUpdate(sql);
			
			// 트렌젝션으로 삽입
			// 그 후에 commit 해줘야함 (connection 객체)
			con.commit();
			con.close();
			// 다 사용한 연결 끊어주기 - DBMS도 무한 접속을 막기 위한 접속제한 있기 때문
			
			if(result > 0) {
				System.out.println("입력 성공!");
			}else {
				System.out.println("입력 실패!");
				System.out.println("error code : ora-13245");
				System.out.println("이 화면을 반복적으로 보게 된다면 관리자에게 문의하세요.");
				System.out.println("02-1111-2222");
			}

			

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

cafe 테이블에 Espresso 삭제

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Exam_02 {
	public static void main(String[] args) {
		//Espresso를 삭제한는 프로그램을 작성해주세요.

		try{
			Class.forName("oracle.jdbc.driver.OracleDriver");
		}catch(Exception e) {
			e.printStackTrace();
		}

		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String loginID = "kh";
		String loginPw = "kh";

		try{
			Connection con = DriverManager.getConnection(url,loginID,loginPw);
		
			Statement stat = con.createStatement();
			
			String sql = "delete from cafe where pname='Espresso'";
			
			int result = stat.executeUpdate(sql);
			
			con.commit();
			con.close();
			
			
			if (result>0) {
				System.out.println("삭제 성공!");
			}else {
				System.out.println("뭔가 잘못되었어요!");
			}
		}catch(Exception e) {
			e.printStackTrace();
		}

	}
}

cafe 테이블에 update 사용해보기

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Exam_03 {

	public static void main(String[] args) {

		try {
			
			Class.forName("oracle.jdbc.driver.OracleDriver");
			
		}catch(Exception e) {
			e.printStackTrace();
			System.out.println("드라이버 클래스 찾을 수 없음!");
		}
		
		
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String user = "kh";
		String password = "kh";
		try {
		Connection con = DriverManager.getConnection(url, user, password);
		
		Statement stat = con.createStatement();
		
		String sql = "update cafe set price=4000 where pname='Hot choco'";
		int result = stat.executeUpdate(sql);
		
		con.commit();
		con.close();
		
		if(result>0) {
			System.out.println("변경 성공!");
		}else {
			System.out.println("변경 실패!");
		}
		
		}catch(Exception e) {
			e.printStackTrace();
		}
	}

}

executeQuery

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Exam_04 {
	public static void main(String[] args) {

		try {

			Class.forName("oracle.jdbc.driver.OracleDriver");

		}catch(Exception e) {
			e.printStackTrace();
			System.out.println("드라이버 클래스 찾을 수 없음!");
		}


		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String user = "kh";
		String password = "kh";
		try {
			Connection con = DriverManager.getConnection(url, user, password);

			Statement stat = con.createStatement();

			String sql = "select * from cafe";

			ResultSet rs = stat.executeQuery(sql);

			if(rs.next()) {
				int pid = rs.getInt("pid");
				String pname = rs.getString("pname");
				int price = rs.getInt("price");
				System.out.println(pid+" : "+pname+" : "+price);
			}
			

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

}


rs.next(); 
// T 다음것 있음,  F 다음것 없음
// 쓸때마다 보고 있는 위치 달라짐

컬럼번호 / 컬럼이름  (오버로딩)


여러줄 꺼내기 - if

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Exam_04 {
	public static void main(String[] args) {

		try {

			Class.forName("oracle.jdbc.driver.OracleDriver");

		}catch(Exception e) {
			e.printStackTrace();
			System.out.println("드라이버 클래스 찾을 수 없음!");
		}


		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String user = "kh";
		String password = "kh";
		try {
			Connection con = DriverManager.getConnection(url, user, password);

			Statement stat = con.createStatement();

			String sql = "select * from cafe";

			ResultSet rs = stat.executeQuery(sql);

			if(rs.next()) {
				int pid = rs.getInt("pid");
				String pname = rs.getString("pname");
				int price = rs.getInt("price");
				System.out.println(pid+" : "+pname+" : "+price);
			}
			if(rs.next()) {
				int pid = rs.getInt("pid");
				String pname = rs.getString("pname");
				int price = rs.getInt("price");
				System.out.println(pid+" : "+pname+" : "+price);
			}
			if(rs.next()) {
				int pid = rs.getInt("pid");
				String pname = rs.getString("pname");
				int price = rs.getInt("price");
				System.out.println(pid+" : "+pname+" : "+price);
			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}
	}

}

여러줄 꺼내기 - while

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Exam_04 {
	public static void main(String[] args) {

		try {

			Class.forName("oracle.jdbc.driver.OracleDriver");

		}catch(Exception e) {
			e.printStackTrace();
			System.out.println("드라이버 클래스 찾을 수 없음!");
		}


		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String user = "kh";
		String password = "kh";
		try {
			Connection con = DriverManager.getConnection(url, user, password);

			Statement stat = con.createStatement();

			String sql = "select * from cafe";

			ResultSet rs = stat.executeQuery(sql);

			while(rs.next()) {
				int pid = rs.getInt("pid");
				String pname = rs.getString("pname");
				int price = rs.getInt("price");
				System.out.println(pid+" : "+pname+" : "+price);
			}
			con.close();
	
			
		}catch(Exception e) {
			e.printStackTrace();
		}
	}

}

예제 프로그램들 CafeManager 클래스의 메서드로 만들기

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class CafeManager {

	public void insert() {

		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");

		}catch(Exception e) {
			System.out.println("드라이버 클래스를 찾을 수 없습니다!! 라이브러리 확인하세요!");
			e.printStackTrace();
			System.exit(0);;
		}
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String loginId = "kh";
		String loginPw = "kh";

		try {


			Connection con = DriverManager.getConnection(url, loginId, loginPw);

			Statement stat = con.createStatement();


			String sql = 
					"insert into cafe values(cafe_seq.nextval,'Espresso',1500)";

			int result = stat.executeUpdate(sql);

			con.commit();
			con.close();

			if(result > 0) {
				System.out.println("입력 성공!");
			}else {
				System.out.println("입력 실패!");
				System.out.println("error code : ora-13245");
				System.out.println("이 화면을 반복적으로 보게 된다면 관리자에게 문의하세요.");
				System.out.println("02-1111-2222");
			}


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

	}

	public void delete() {
		try{
			Class.forName("oracle.jdbc.driver.OracleDriver");
		}catch(Exception e) {
			e.printStackTrace();
		}

		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String loginID = "kh";
		String loginPw = "kh";

		try{
			Connection con = DriverManager.getConnection(url,loginID,loginPw);

			Statement stat = con.createStatement();

			String sql = "delete from cafe where pname='Espresso'";

			int result = stat.executeUpdate(sql);

			con.commit();
			con.close();

			if (result>0) {
				System.out.println("삭제 성공!");
			}else {
				System.out.println("뭔가 잘못되었어요!");
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}

	public void update() {

		try {

			Class.forName("oracle.jdbc.driver.OracleDriver");

		}catch(Exception e) {
			e.printStackTrace();
			System.out.println("드라이버 클래스 찾을 수 없음!");
		}


		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String user = "kh";
		String password = "kh";
		try {
			Connection con = DriverManager.getConnection(url, user, password);

			Statement stat = con.createStatement();

			String sql = "update cafe set price=4000 where pname='Hot choco'";
			int result = stat.executeUpdate(sql);

			con.commit();
			con.close();

			if(result>0) {
				System.out.println("변경 성공!");
			}else {
				System.out.println("변경 실패!");
			}

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

	}

	public void select() {

		try {

			Class.forName("oracle.jdbc.driver.OracleDriver");

		}catch(Exception e) {
			e.printStackTrace();
			System.out.println("드라이버 클래스 찾을 수 없음!");
		}


		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String user = "kh";
		String password = "kh";
		try {
			Connection con = DriverManager.getConnection(url, user, password);

			Statement stat = con.createStatement();

			String sql = "select * from cafe";

			ResultSet rs = stat.executeQuery(sql);

			while(rs.next()) {
				int pid = rs.getInt("pid");
				String pname = rs.getString("pname");
				int price = rs.getInt("price");
				System.out.println(pid+" : "+pname+" : "+price);
			}
			con.close();


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

	}

}
public class Main {
	public static void main(String[] args) {

		CafeManager manager = new CafeManager();
		manager.insert();
		manager.delete();
		manager.update();
		manager.select();
		
	}

}

CafeManager 내의 코드 중복 & 수정값 정해져 있음

이미 만들어진 코드를 최적화 : 리팩토링 

 

--반복되는 코드
	try {
			Class.forName("oracle.jdbc.driver.OracleDriver");

		}catch(Exception e) {
			System.out.println("드라이버 클래스를 찾을 수 없습니다!! 라이브러리 확인하세요!");
			e.printStackTrace();
			System.exit(0);;
		}
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String loginId = "kh";
		String loginPw = "kh";

커넥션 매서드 만들기

	public Connection makeConnection() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");

		}catch(Exception e) {
			System.out.println("드라이버 클래스를 찾을 수 없습니다!! 라이브러리 확인하세요!");
			e.printStackTrace();
			System.exit(0);;
		}
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String loginId = "kh";
		String loginPw = "kh";
		
		Connection con = DriverManager.getConnection(url, loginId, loginPw);
		return con;
	}

예외 발생

try catch : 예상범위 내에서의 문제 , 사용자가 처리 할 수 없으니 내가 처리해야해 예외처리

throws exception : 예상 밖의 문제, 개발자 설계자가 해결 할 수 없음 예외전가

 

main에서 throws 시킬 곳이 없음, main이 최종사용자

 

출력부, 그래픽 부분은 메서드가 아닌 main에

makeConnection 메서드에서 트라이캐치로 콘솔 출력시엔 다른 환경(그래픽)에서 범용성 떨어짐

 

	public Connection makeConnection() throws Exception {

		Class.forName("oracle.jdbc.driver.OracleDriver");

		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String loginId = "kh";
		String loginPw = "kh";
		
		Connection con = DriverManager.getConnection(url, loginId, loginPw);
		return con;
	}

반복되는 코드가 상당부분 줄었다.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class CafeManager {

	public Connection makeConnection() throws Exception {

		Class.forName("oracle.jdbc.driver.OracleDriver");

		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String loginId = "kh";
		String loginPw = "kh";
		
		Connection con = DriverManager.getConnection(url, loginId, loginPw);
		return con;
	}
	
	
	public void insert() {

		try {

			Connection con = makeConnection();

			Statement stat = con.createStatement();


			String sql = 
					"insert into cafe values(cafe_seq.nextval,'Espresso',1500)";

			int result = stat.executeUpdate(sql);

			con.commit();
			con.close();

			if(result > 0) {
				System.out.println("입력 성공!");
			}else {
				System.out.println("입력 실패!");
				System.out.println("error code : ora-13245");
				System.out.println("이 화면을 반복적으로 보게 된다면 관리자에게 문의하세요.");
				System.out.println("02-1111-2222");
			}


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

	}

	public void delete() {


		try{
			Connection con = makeConnection();

			Statement stat = con.createStatement();

			String sql = "delete from cafe where pname='Espresso'";

			int result = stat.executeUpdate(sql);

			con.commit();
			con.close();

			if (result>0) {
				System.out.println("삭제 성공!");
			}else {
				System.out.println("뭔가 잘못되었어요!");
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}

	public void update() {


		try {
			Connection con = makeConnection();

			Statement stat = con.createStatement();

			String sql = "update cafe set price=4000 where pname='Hot choco'";
			int result = stat.executeUpdate(sql);

			con.commit();
			con.close();

			if(result>0) {
				System.out.println("변경 성공!");
			}else {
				System.out.println("변경 실패!");
			}

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

	}

	public void select() {


		try {
			Connection con = makeConnection();

			Statement stat = con.createStatement();

			String sql = "select * from cafe";

			ResultSet rs = stat.executeQuery(sql);

			while(rs.next()) {
				int pid = rs.getInt("pid");
				String pname = rs.getString("pname");
				int price = rs.getInt("price");
				System.out.println(pid+" : "+pname+" : "+price);
			}
			con.close();


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

	}

}

전가된 예외는?

throws Exception : 자신을 call 한 위치에 예외를 보낸다.

	public void insert() {

		try {

			Connection con = makeConnection(); // 여기로 예외전가 되어옴
            // 여기서는 받은 예외를 try catch로 예외처리
			// try catch가 없다면 에러
            
			Statement stat = con.createStatement();

			String sql = 
					"insert into cafe values(cafe_seq.nextval,'Espresso',1500)";

			int result = stat.executeUpdate(sql);

			con.commit();
			con.close();

			if(result > 0) {
				System.out.println("입력 성공!");
			}else {
				System.out.println("입력 실패!");
				System.out.println("error code : ora-13245");
				System.out.println("이 화면을 반복적으로 보게 된다면 관리자에게 문의하세요.");
				System.out.println("02-1111-2222");
			}


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

	}

CafeManager는 DB관련 작업만 할 것

출력관련 작업( try catch에러메세지, sysout메세지 )는 main에서 처리 하도록 만들것

단, 결과를 전달해주긴 해야함

	public int insert() throws Exception {


			Connection con = makeConnection();

			Statement stat = con.createStatement();


			String sql = 
					"insert into cafe values(cafe_seq.nextval,'Espresso',1500)";

			int result = stat.executeUpdate(sql);

			con.commit();
			con.close();

			return result;
	}

template extraction method

 

출력외 예외 관련 기능을 빼야 범용성, 이식성 좋아짐

 

mvc model

 

refactoring


 

 

 

예외전가 : callee method가 예외를 caller method에게 전가하는 것

main은 자체가 프로그램, 예외전가를 하지 못함, 만약 한다면 프로그램을 꺼버리는 무책임한 경우


전가 받을 예외를 어떻게 할 것인가?

 

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {

		CafeManager manager = new CafeManager();

		Scanner sc = new Scanner(System.in);
		System.out.println("=== 카페 메뉴 관리 프로그램 ===");
		System.out.println("1. 신규 메뉴 등록");
		System.out.println("2. 메뉴 수정");
		System.out.print("선택 > ");
		String menu = sc.nextLine();

		if(menu.contentEquals("1")) {
			try {
				int result = manager.insert();
				if(result>0) {
					System.out.println("성공적으로 입력되었습니다.");
				}else {
					System.out.println("알 수 없는 이유로 입력에 실패했습니다.");
				}
			}catch(Exception e) {
				e.printStackTrace();
				System.out.println("입력의 오류가 발생했습니다.");
				System.out.println("시스템 관리자에게 문의하세요.");
				System.out.println("02-1234-1324");
			}
		}else if(menu.contentEquals("2")) {
//			manager.update();
		}

	}

}

품명과 가격을 입력 받기

: cafeManager로 입력받게 했다가 입력을 그래픽으로 받는다면? : 이식성 떨어짐

 

 


에러 발생 " "

			String sql = 
					"insert into cafe values(cafe_seq.nextval,'pname', price)";
// 에러 발생
			String sql = 
					"insert into cafe values(cafe_seq.nextval,'"+pname+"', "+price+")";
                    //동작

삽입 기능 완성

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {

		CafeManager manager = new CafeManager();

		Scanner sc = new Scanner(System.in);
		System.out.println("=== 카페 메뉴 관리 프로그램 ===");
		System.out.println("1. 신규 메뉴 등록");
		System.out.println("2. 메뉴 수정");
		System.out.print("선택 > ");
		String menu = sc.nextLine();

		if(menu.contentEquals("1")) {
			
			System.out.println("품명을 입력하세요 : ");
			String pname = sc.nextLine();
			
			System.out.println("가격을 입력하세요 : ");
			int price = Integer.parseInt(sc.nextLine());
			
			try {
				int result = manager.insert(pname, price);
				if(result>0) {
					System.out.println("성공적으로 입력되었습니다.");
				}else {
					System.out.println("알 수 없는 이유로 입력에 실패했습니다.");
				}
			}catch(Exception e) {
				e.printStackTrace();
				System.out.println("입력의 오류가 발생했습니다.");
				System.out.println("시스템 관리자에게 문의하세요.");
				System.out.println("02-1234-1324");
			}
		}else if(menu.contentEquals("2")) {
//			manager.update();
		}

	}

}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class CafeManager {

	public Connection makeConnection() throws Exception {

		Class.forName("oracle.jdbc.driver.OracleDriver");

		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String loginId = "kh";
		String loginPw = "kh";
		
		Connection con = DriverManager.getConnection(url, loginId, loginPw);
		return con;
	}
	
	
	public int insert(String pname, int price) throws Exception {
			Connection con = makeConnection();
			Statement stat = con.createStatement();
			String sql = 
					"insert into cafe values(cafe_seq.nextval,'"+pname+"', "+price+")";
			int result = stat.executeUpdate(sql);
			con.commit();
			con.close();
			return result;
	}

	
	public int delete() throws Exception {

			Connection con = makeConnection();

			Statement stat = con.createStatement();

			String sql = "delete from cafe where pname='Espresso'";

			int result = stat.executeUpdate(sql);

			con.commit();
			con.close();

			return result;

	}

	public int update() throws Exception {



			Connection con = makeConnection();

			Statement stat = con.createStatement();

			String sql = "update cafe set price=4000 where pname='Hot choco'";
			int result = stat.executeUpdate(sql);

			con.commit();
			con.close();

			return result;
	}

	public void select() {


		try {
			Connection con = makeConnection();

			Statement stat = con.createStatement();

			String sql = "select * from cafe";

			ResultSet rs = stat.executeQuery(sql);

			while(rs.next()) {
				int pid = rs.getInt("pid");
				String pname = rs.getString("pname");
				int price = rs.getInt("price");
				System.out.println(pid+" : "+pname+" : "+price);
			}
			con.close();


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

	}

}

 


삭제, 수정 기능 완성

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {

		CafeManager manager = new CafeManager();

		Scanner sc = new Scanner(System.in);
		System.out.println("=== 카페 메뉴 관리 프로그램 ===");
		System.out.println("1. 신규 메뉴 등록");
		System.out.println("2. 메뉴 삭제");
		System.out.println("3. 메뉴 수정");
		System.out.print("선택 > ");
		String menu = sc.nextLine();

		if(menu.contentEquals("1")) {
			
			System.out.println("품명을 입력하세요 : ");
			String pname = sc.nextLine();
			
			System.out.println("가격을 입력하세요 : ");
			int price = Integer.parseInt(sc.nextLine());
			
			try {
				int result = manager.insert(pname, price);
				if(result>0) {
					System.out.println("성공적으로 입력되었습니다.");
				}else {
					System.out.println("알 수 없는 이유로 입력에 실패했습니다.");
				}
			}catch(Exception e) {
				e.printStackTrace();
				System.out.println("입력의 오류가 발생했습니다.");
				System.out.println("시스템 관리자에게 문의하세요.");
				System.out.println("02-1234-1324");
			}
		}else if(menu.contentEquals("2")) {
			
			System.out.println("항목ID를 입력하세요 : ");
			int pid = Integer.parseInt(sc.nextLine());

			
			try {
				int result = manager.delete(pid);
				
				if(result>0) {
					System.out.println("성공적으로 삭제되었습니다.");
				}else {
					System.out.println("알 수 없는 이유로 입력에 실패했습니다.");
				}
				
			}catch(Exception e) {
				e.printStackTrace();
				System.out.println("입력의 오류가 발생했습니다.");
				System.out.println("시스템 관리자에게 문의하세요.");
				System.out.println("02-1234-1324");
			}
			
			
		}else if(menu.contentEquals("3")) {
			
			System.out.println("항목ID를 입력하세요 : ");
			int pid = Integer.parseInt(sc.nextLine());
			System.out.println("변경할 품명을 입력하세요 : ");
			String pname = sc.nextLine();
			System.out.println("변경할 가격을 입력하세요 : ");
			int price = Integer.parseInt(sc.nextLine());
			
			try {
				int result = manager.update(pid,pname,price);
				
				if(result>0) {
					System.out.println("성공적으로 변경되었습니다.");
				}else {
					System.out.println("알 수 없는 이유로 입력에 실패했습니다.");
				}
				
			}catch(Exception e) {
				e.printStackTrace();
				System.out.println("입력의 오류가 발생했습니다.");
				System.out.println("시스템 관리자에게 문의하세요.");
				System.out.println("02-1234-1324");
			}
		}
	}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class CafeManager {

	public Connection makeConnection() throws Exception {

		Class.forName("oracle.jdbc.driver.OracleDriver");

		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String loginId = "kh";
		String loginPw = "kh";
		
		Connection con = DriverManager.getConnection(url, loginId, loginPw);
		return con;
	}
	
	
	public int insert(String pname, int price) throws Exception {
			Connection con = makeConnection();
			Statement stat = con.createStatement();
			String sql = 
					"insert into cafe values(cafe_seq.nextval,'"+pname+"', "+price+")";
			int result = stat.executeUpdate(sql);
			con.commit();
			con.close();
			return result;
	}

	
	public int delete(int pid) throws Exception {

			Connection con = makeConnection();
			Statement stat = con.createStatement();
			String sql = "delete from cafe where pid="+pid;

			int result = stat.executeUpdate(sql);

			con.commit();
			con.close();

			return result;

	}

	public int update(int pid, String pname, int price) throws Exception {

			Connection con = makeConnection();
			Statement stat = con.createStatement();
			String sql = "update cafe set pname = '"+pname+"' , price="+price+"  where pid="+pid;
			int result = stat.executeUpdate(sql);
			con.commit();
			con.close();
			return result;
	}

	public void select() {


		try {
			Connection con = makeConnection();

			Statement stat = con.createStatement();

			String sql = "select * from cafe";

			ResultSet rs = stat.executeQuery(sql);

			while(rs.next()) {
				int pid = rs.getInt("pid");
				String pname = rs.getString("pname");
				int price = rs.getInt("price");
				System.out.println(pid+" : "+pname+" : "+price);
			}
			con.close();


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

검색 기능

	public void searchById(int pid) throws Exception {
		
		Connection con = this.makeConnection();
		Statement stat = con. createStatement();
		String sql = "select * from cafe where id ="+pid;
		ResultSet rs = stat.executeQuery(sql);
		//어쩌피 한줄이니 while 보다는 if
		if(rs.next()) {
			int id = rs.getInt("pid");
			String name =rs.getString("pname");
			int price = rs.getInt("price");
		}
		con.close();
	}

resultset으로 반환 못함

 

배열은 번호로 관리해야 하고 다운캐스팅 필요

(오브젝트 배열은 다형성을 가져서 여러 자료형을 가질수 있지만 쓸때마다 다운캐스팅 해야함 그래서 제너릭을 사용)

 

학번 + 이름 + 성적 -> 학생

품번 + 이름 + 가격 -> 메뉴 (새로운 자료형을 만들기)


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {

		CafeManager manager = new CafeManager();

		Scanner sc = new Scanner(System.in);
		System.out.println("=== 카페 메뉴 관리 프로그램 ===");
		System.out.println("1. 신규 메뉴 등록");
		System.out.println("2. 메뉴 삭제");
		System.out.println("3. 메뉴 수정");
		System.out.println("4. 메뉴 검색");
		System.out.print("선택 > ");
		String menu = sc.nextLine();

		if(menu.contentEquals("1")) {

			System.out.println("품명을 입력하세요 : ");
			String pname = sc.nextLine();

			System.out.println("가격을 입력하세요 : ");
			int price = Integer.parseInt(sc.nextLine());

			try {
				int result = manager.insert(pname, price);
				if(result>0) {
					System.out.println("성공적으로 입력되었습니다.");
				}else {
					System.out.println("알 수 없는 이유로 입력에 실패했습니다.");
				}
			}catch(Exception e) {
				e.printStackTrace();
				System.out.println("입력의 오류가 발생했습니다.");
				System.out.println("시스템 관리자에게 문의하세요.");
				System.out.println("02-1234-1324");
			}
		}else if(menu.contentEquals("2")) {

			System.out.println("항목ID를 입력하세요 : ");
			int pid = Integer.parseInt(sc.nextLine());


			try {
				int result = manager.delete(pid);

				if(result>0) {
					System.out.println("성공적으로 삭제되었습니다.");
				}else {
					System.out.println("알 수 없는 이유로 입력에 실패했습니다.");
				}

			}catch(Exception e) {
				e.printStackTrace();
				System.out.println("입력의 오류가 발생했습니다.");
				System.out.println("시스템 관리자에게 문의하세요.");
				System.out.println("02-1234-1324");
			}


		}else if(menu.contentEquals("3")) {

			System.out.println("항목ID를 입력하세요 : ");
			int pid = Integer.parseInt(sc.nextLine());
			System.out.println("변경할 품명을 입력하세요 : ");
			String pname = sc.nextLine();
			System.out.println("변경할 가격을 입력하세요 : ");
			int price = Integer.parseInt(sc.nextLine());

			try {
				int result = manager.update(pid,pname,price);

				if(result>0) {
					System.out.println("성공적으로 변경되었습니다.");
				}else {
					System.out.println("알 수 없는 이유로 입력에 실패했습니다.");
				}

			}catch(Exception e) {
				e.printStackTrace();
				System.out.println("입력의 오류가 발생했습니다.");
				System.out.println("시스템 관리자에게 문의하세요.");
				System.out.println("02-1234-1324");
			}
		}else if(menu.contentEquals("4")) {
			
			System.out.println("아이디 입력 : ");
			int id = Integer.parseInt(sc.nextLine());
			
			try {
				Menu cafeMenu = manager.searchById(id);
				
				System.out.println("상품ID\t상품명\t가격");
				System.out.println(cafeMenu.getPid()+"\t"+
									cafeMenu.getPname()+"\t"+
									cafeMenu.getPrice());
				
			}catch(Exception e) {
				e.printStackTrace();
				System.out.println("오류발생");
			}
			
			
			
		}
	}

}


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;



public class CafeManager {

	public Connection makeConnection() throws Exception {

		Class.forName("oracle.jdbc.driver.OracleDriver");

		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String loginId = "kh";
		String loginPw = "kh";
		
		Connection con = DriverManager.getConnection(url, loginId, loginPw);
		return con;
	}
	
	
	public int insert(String pname, int price) throws Exception {
			Connection con = makeConnection();
			Statement stat = con.createStatement();
			String sql = 
					"insert into cafe values(cafe_seq.nextval,'"+pname+"', "+price+")";
			int result = stat.executeUpdate(sql);
			con.commit();
			con.close();
			return result;
	}

	
	public int delete(int pid) throws Exception {

			Connection con = makeConnection();
			Statement stat = con.createStatement();
			String sql = "delete from cafe where pid="+pid;

			int result = stat.executeUpdate(sql);

			con.commit();
			con.close();

			return result;

	}

	public int update(int pid, String pname, int price) throws Exception {

			Connection con = makeConnection();
			Statement stat = con.createStatement();
			String sql = "update cafe set pname = '"+pname+"' , price="+price+"  where pid="+pid;
			int result = stat.executeUpdate(sql);
			con.commit();
			con.close();
			return result;
	}

	public void select() {


		try {
			Connection con = makeConnection();

			Statement stat = con.createStatement();

			String sql = "select * from cafe";

			ResultSet rs = stat.executeQuery(sql);

			while(rs.next()) {
				int pid = rs.getInt("pid");
				String pname = rs.getString("pname");
				int price = rs.getInt("price");
				System.out.println(pid+" : "+pname+" : "+price);
			}
			con.close();


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

	}

	public Menu searchById(int pid) throws Exception {
		
		Connection con = this.makeConnection();
		Statement stat = con. createStatement();
		String sql = "select * from cafe where pid ="+pid;
		ResultSet rs = stat.executeQuery(sql);
		//어쩌피 한줄이니 while 보다는 if
		
		Menu menu = null; 
		if(rs.next()) {
			int id = rs.getInt("pid");
			String name =rs.getString("pname");
			int price = rs.getInt("price");
			menu = new Menu(id,name,price);
		}
		
		con.close();
		return menu;
		
	}
	
}
public class Menu {
	
		private int pid;
		private String pname;
		private int price;
		
		public Menu(int pid, String pname, int price) {
			
			this.pid = pid;
			this.pname = pname;
			this.price = price;
		}
		public int getPid() {
			return pid;
		}
		public void setPid(int pid) {
			this.pid = pid;
		}
		public String getPname() {
			return pname;
		}
		public void setPname(String pname) {
			this.pname = pname;
		}
		public int getPrice() {
			return price;
		}
		public void setPrice(int price) {
			this.price = price;
		}
		
	
}

 


메뉴 목록 구현

public class Menu {
	
		private int pid;
		private String pname;
		private int price;
		
		public Menu(int pid, String pname, int price) {
			
			this.pid = pid;
			this.pname = pname;
			this.price = price;
		}
		public int getPid() {
			return pid;
		}
		public void setPid(int pid) {
			this.pid = pid;
		}
		public String getPname() {
			return pname;
		}
		public void setPname(String pname) {
			this.pname = pname;
		}
		public int getPrice() {
			return price;
		}
		public void setPrice(int price) {
			this.price = price;
		}
		
	
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;



public class CafeManager {

	public Connection makeConnection() throws Exception {

		Class.forName("oracle.jdbc.driver.OracleDriver");

		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String loginId = "kh";
		String loginPw = "kh";

		Connection con = DriverManager.getConnection(url, loginId, loginPw);
		return con;
	}


	public int insert(String pname, int price) throws Exception {
		Connection con = makeConnection();
		Statement stat = con.createStatement();
		String sql = 
				"insert into cafe values(cafe_seq.nextval,'"+pname+"', "+price+")";
		int result = stat.executeUpdate(sql);
		con.commit();
		con.close();
		return result;
	}


	public int delete(int pid) throws Exception {

		Connection con = makeConnection();
		Statement stat = con.createStatement();
		String sql = "delete from cafe where pid="+pid;

		int result = stat.executeUpdate(sql);

		con.commit();
		con.close();

		return result;

	}

	public int update(int pid, String pname, int price) throws Exception {

		Connection con = makeConnection();
		Statement stat = con.createStatement();
		String sql = "update cafe set pname = '"+pname+"' , price="+price+"  where pid="+pid;
		int result = stat.executeUpdate(sql);
		con.commit();
		con.close();
		return result;
	}

	//menu 제너릭 List를 리턴
	public List<Menu> select() throws Exception {

		Connection con = makeConnection();
		Statement stat = con.createStatement();
		String sql = "select * from cafe";
		ResultSet rs = stat.executeQuery(sql);
		List<Menu> menus = new ArrayList<>();
		while(rs.next()) {
			int pid = rs.getInt("pid");
			String pname = rs.getString("pname");
			int price = rs.getInt("price");
			menus.add(new Menu(pid,pname,price));
		}
		con.close();
		return menus;
	}

	public Menu searchById(int pid) throws Exception {

		Connection con = this.makeConnection();
		Statement stat = con. createStatement();
		String sql = "select * from cafe where pid ="+pid;
		ResultSet rs = stat.executeQuery(sql);
		//어쩌피 한줄이니 while 보다는 if

		Menu menu = null; 
		if(rs.next()) {
			int id = rs.getInt("pid");
			String name =rs.getString("pname");
			int price = rs.getInt("price");
			menu = new Menu(id,name,price);
		}

		con.close();
		return menu;

	}
}
import java.util.List;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {

		CafeManager manager = new CafeManager();

		Scanner sc = new Scanner(System.in);
		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.print("선택 > ");
		String menu = sc.nextLine();

		if(menu.contentEquals("1")) {

			System.out.println("품명을 입력하세요 : ");
			String pname = sc.nextLine();

			System.out.println("가격을 입력하세요 : ");
			int price = Integer.parseInt(sc.nextLine());

			try {
				int result = manager.insert(pname, price);
				if(result>0) {
					System.out.println("성공적으로 입력되었습니다.");
				}else {
					System.out.println("알 수 없는 이유로 입력에 실패했습니다.");
				}
			}catch(Exception e) {
				e.printStackTrace();
				System.out.println("입력의 오류가 발생했습니다.");
				System.out.println("시스템 관리자에게 문의하세요.");
				System.out.println("02-1234-1324");
			}
		}else if(menu.contentEquals("2")) {

			System.out.println("항목ID를 입력하세요 : ");
			int pid = Integer.parseInt(sc.nextLine());


			try {
				int result = manager.delete(pid);

				if(result>0) {
					System.out.println("성공적으로 삭제되었습니다.");
				}else {
					System.out.println("알 수 없는 이유로 입력에 실패했습니다.");
				}

			}catch(Exception e) {
				e.printStackTrace();
				System.out.println("입력의 오류가 발생했습니다.");
				System.out.println("시스템 관리자에게 문의하세요.");
				System.out.println("02-1234-1324");
			}


		}else if(menu.contentEquals("3")) {

			System.out.println("항목ID를 입력하세요 : ");
			int pid = Integer.parseInt(sc.nextLine());
			System.out.println("변경할 품명을 입력하세요 : ");
			String pname = sc.nextLine();
			System.out.println("변경할 가격을 입력하세요 : ");
			int price = Integer.parseInt(sc.nextLine());

			try {
				int result = manager.update(pid,pname,price);

				if(result>0) {
					System.out.println("성공적으로 변경되었습니다.");
				}else {
					System.out.println("알 수 없는 이유로 입력에 실패했습니다.");
				}

			}catch(Exception e) {
				e.printStackTrace();
				System.out.println("입력의 오류가 발생했습니다.");
				System.out.println("시스템 관리자에게 문의하세요.");
				System.out.println("02-1234-1324");
			}
		}else if(menu.contentEquals("4")) {

			System.out.println("아이디 입력 : ");
			int id = Integer.parseInt(sc.nextLine());

			try {
				Menu cafeMenu = manager.searchById(id);

				System.out.println("상품ID\t상품명\t가격");
				System.out.println(cafeMenu.getPid()+"\t"+
						cafeMenu.getPname()+"\t"+
						cafeMenu.getPrice());

			}catch(Exception e) {
				e.printStackTrace();
				System.out.println("오류발생");
			}



		}else if(menu.contentEquals("5")) {


			try {
				List<Menu> menus = manager.select();

		
				System.out.println("상품ID\t상품명\t가격");
				for(Menu tmp : menus) {
					System.out.println(tmp.getPid()+"\t"+
							tmp.getPname()+"\t"+
							tmp.getPrice()
							);
				}
				
			}catch(Exception e) {
				e.printStackTrace();
				System.out.println("오류발생");
			}
		}
	}
}