TIL 0322

먼지·2024년 3월 22일

Today I Learned

목록 보기
25/89
post-thumbnail

NOTE 테이블 & 시퀀스 생성

CREATE TABLE note (
num NUMBER PRIMARY KEY,
name VARCHAR2(30) NOT NULL,
passwd VARCHAR2(10) NOT NULL,
subject VARCHAR2(60)	 NOT NULL,
content VARCHAR2(4000) NOT NULL,
email VARCHAR2(60),
reg_date DATE NOT NULL	
);

CREATE SEQUENCE note_seq;

NOTE DAO 생성

DAO : Data Access Object
데이터베이스의 데이터를 전문적으로 호출하고 제어하는 객체

package kr.s36.jdbc.note;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.*;

import kr.util.DBUtil;
public class NoteDAO {
	//글쓰기
	public void insertInfo ( String name, String passwd, String subject, String content, String email) {
		Connection conn = null;
		PreparedStatement  pstmt= null;
		String sql = null;
		try {
			//JDBC 1단계
			conn = DBUtil.getConnection();

			//SQL문 작성
			sql = "INSERT INTO note VALUES(note_seq.nextval,?,?,?,?,?,SYSDATE)";

			//JDBC 수행 3단계
			pstmt = conn.prepareStatement(sql);

			//?에 데이터 바인딩
			pstmt.setString(1, name);
			pstmt.setString(2, passwd);
			pstmt.setString(3, subject);
			pstmt.setString(4, content);
			pstmt.setString(5, email);

			//JDBC 수행 4단계
			int count = pstmt.executeUpdate(); 
			System.out.println(count + "개의 행을 삽입했습니다.");

		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBUtil.executeClose(null, pstmt, conn);
		}
	}

	//목록 보기
	public void selectInfo() {
		Connection conn = null;
		PreparedStatement  pstmt= null;
		String sql = null;
		ResultSet rs = null;
		try {//JDBC 수행문 1, 2단계
			conn = DBUtil.getConnection();
			//SQL문 작성
			sql = "SELECT * FROM note ORDER BY num DESC";
			//JDBC 수행 3단계 --- SQL문 전달
			pstmt = conn.prepareStatement(sql);
			//JDBC 수행 4단계 : SQL 문장을 실행해서 테이블에 반영하고 
			//						결과 집합을 ReqsultSet에 담아서 반환하기
			rs = pstmt.executeQuery();
			System.out.println("========");
			if(rs.next()) {
				System.out.println("번호\t이름\t작성일\t\t제목");
				do {
					System.out.print(rs.getInt("num"));
					System.out.print("\t");
					System.out.print(rs.getString("name"));
					System.out.print("\t");
					System.out.print(rs.getDate("reg_date"));
					System.out.print("\t");
					System.out.println(rs.getString("subject"));
				} 
				while(rs.next());
			} //end of if
			else {
				System.out.println("표시할 데이터가 없습니다.");
			}
			System.out.println("========");
		}

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

		finally {
			//자원 정리
			DBUtil.executeClose(rs, pstmt, conn);
		}

	}

	//상세글 보기
	public void selectDetailInfo(int num)	{
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = null;
		ResultSet rs = null;
		
		try {
			//JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			//SQL문 작성
			sql = "SELECT * FROM note WHERE num=?";
			//JDBC 수행 3단계 : PreparedStatement 객체 생성
			pstmt = conn.prepareStatement(sql);
			//?에 입력된 값 바인딩
			pstmt.setInt(1, num);
			//JDBC 수행 4 단계 : SQL문을 테이블에 반영하고 결과 집합을 Result Set에 담아서 반환
			rs = pstmt.executeQuery();
			
			//rs.next 값이 primary key에 있는 데이터라면 true를 반환하고 없다면 false를 반환하기 때문에 조건체크를 통해서 출력해야한다
			if (rs.next()) {
				System.out.println("글번호 : " + rs.getInt("num"));
				System.out.println("이름 : " + rs.getString("name"));
				System.out.println("비밀번호 : " + rs.getString("passwd"));
				System.out.println("제목 : " + rs.getString("subject"));
				System.out.println("내용 : " + rs.getString("content"));
				String email = rs.getString("email");
				if(email == null) { // email이 null값이라면 비어있게 출력할 수 있게 조건 체크
					email = ""; }
				System.out.println("이메일 : " + email);
				System.out.println("작성일 : " + rs.getDate("reg_date"));
			}
			else {
				System.out.println("검색된 데이터가 없습니다.");
			}
			
		} 
		catch (Exception e) {
			e.printStackTrace();
		} 
		finally {
			DBUtil.executeClose(rs, pstmt, conn);
		}
	}
	
	
	//수정 작업
	public void updateInfo(int num , String name, String passwd, String subject,String content, String email) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = null;
		try {
				//JDBC 수행문 1,2 단계
				conn = DBUtil.getConnection();
				//SQL문 작성
				sql = "UPDATE note SET name=?,passwd=?,subject=?,content = ?,email=? WHERE num=?";
				//JDBC 수행 3단계
				pstmt = conn.prepareStatement(sql);

				//?에 데이터 바인딩
				pstmt.setString(1, name);
				pstmt.setString(2, passwd);
				pstmt.setString(3, subject);
				pstmt.setString(4, content);
				pstmt.setString(5, email);
				pstmt.setInt(6, num);
				
				//JDBC 수행 4단계 : SQL문을 실행해서 테이블의 데이터를 수정한다.
				int count = pstmt.executeUpdate();
				System.out.println(count+"개 행의 정보를 수정했습니다.");

		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBUtil.executeClose(null, pstmt, conn);
		}
	}
	//글 삭제
	public void deleteInfo(int num) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = null;
		
		try {
			//JDBC 수행 1, 2 단계
			conn = DBUtil.getConnection();
			//SQL문 작성
			sql = "DELETE FROM note WHERE num = ?";
			//JDBC 수행 3 단계
			pstmt= conn.prepareStatement(sql);
			pstmt.setInt(1, num);
			//JDBC 수행 4단계
			int count = pstmt.executeUpdate();
			System.out.println( count + "개 행을 삭제했습니다.");
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//자원 정리
			DBUtil.executeClose(null, pstmt, conn);
		}
		
	}
}

NOTE Main 생성

package kr.s36.jdbc.note;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class NoteMain {
	private BufferedReader br;
	private NoteDAO note;

	//생성자
	public NoteMain()	{
		try {
			br = new BufferedReader(new InputStreamReader(System.in));
			note = new NoteDAO();

			//메뉴 호출
			callMenu();

		}

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

		finally {
			if(br != null) try {br.close();} catch(IOException e) {}
		}

	}
	//메뉴
	public void callMenu()	throws IOException {
		while(true) {
			System.out.print( "1. 글쓰기 | 2. 목록 보기 | 3. 상세글 보기 | 4. 글 수정 | 5. 글 삭제 | 6. 종료 | >");
			try {
				int no = Integer.parseInt(br.readLine());
				
				if ( no == 1) {// 글 쓰기
					
					System.out.print("이름 : ");
					String name = br.readLine();
					System.out.print("비밀번호 : ");
					String passwd = br.readLine();
					System.out.print("제목 : ");
					String subject = br.readLine();
					System.out.print("내용 : ");
					String content = br.readLine();
					System.out.print("이메일 : ");
					String email = br.readLine();
					// noteDAO/insertInfo 메소드 호출해서 입력받은 데이터 전달하기
					note.insertInfo(name, passwd, subject, content, email);
				}
				else if( no == 2 ) {// 목록 보기
					note.selectInfo();
				}
				else if( no == 3 ) { // 상세글 보기
					System.out.print("선택한 글의 번호 : ");
					int num = Integer.parseInt(br.readLine());
					
					note.selectDetailInfo(num);
				}
				else if( no == 4 ) {// 글 수정
					System.out.print("수정할 글의 번호 : ");
					int num = Integer.parseInt(br.readLine());
					note.selectDetailInfo(num);
					System.out.println("=====");
					System.out.print("이름 : ");
					String name = br.readLine();
					System.out.print("비밀번호 : ");
					String passwd = br.readLine();
					System.out.print("제목 : ");
					String subject = br.readLine();
					System.out.print("내용 : ");
					String content = br.readLine();
					System.out.print("이메일 : ");
					String email = br.readLine();
					
					note.updateInfo(num,name, passwd, subject, content, email);
					
				}
				else if( no == 5 ) {// 글 삭제
					note.selectInfo();
					
					System.out.print("삭제할 글의 번호 : ");
					int num = Integer.parseInt(br.readLine());
					
					note.deleteInfo(num);
				}
				else if (no == 6){// 프로그램 종료
					System.out.println("프로그램을 종료합니다.");
					break;
				}
				else {
					System.out.println("잘못 입력하셨습니다.");
				}
				
			} catch (NumberFormatException e) {
				System.out.println("숫자만 입력 가능합니다.");
			}
		}

	}

	public static void main(String[] args) {
		new NoteMain();

	}

}

Create Car Table & Sequence

CREATE TABLE car (
num NUMBER PRIMARY KEY,
name VARCHAR2(30)NOT NULL, --이름
cnumber VARCHAR2(30) NOT NULL, -- 차번호
color VARCHAR2(30) NOT NULL,  -- 차 색상
maker VARCHAR2(30) NOT NULL, --차 제조사
price NUMBER(10) NOT NULL, -- 차량 가격
reg_date DATE NOT NULL -- 차량 등록일
);

CREATE SEQUENCE car_seq;

CarDAO

package kr.s37.jdbc.car;

import java.sql.*;
import kr.util.DBUtil;

public class CarDAO {

	//자동차 정보 등록
	public void insertCar(String name, String cnumber, String color, String maker, int price) {
		Connection conn = null;
		PreparedStatement pstmt= null;
		String sql = null;
		try {
			//JDBC 수행 1,2단계
			conn = DBUtil.getConnection();

			//SQL문 입력하기
			sql = "INSERT INTO car VALUES(car_seq.nextval,?,?,?,?,?,SYSDATE)";

			//JDBC 수행 3단계
			pstmt = conn.prepareStatement(sql);

			//?에 데이터 바인딩
			pstmt.setString(1,name);
			pstmt.setString(2, cnumber);
			pstmt.setString(3, color);
			pstmt.setString(4, maker);
			pstmt.setInt(5, price);

			//JDBC 수행 4단계
			int count = pstmt.executeUpdate();
			System.out.println(count + "개의 행을 삽입했습니다.");

		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBUtil.executeClose(null, pstmt, conn);
		}
	} // insertCAR end

	//목록 보기
	public void selectCar() {
		Connection conn = null;
		PreparedStatement pstmt= null;
		String sql = null;
		ResultSet rs = null;
		try {
			conn = DBUtil.getConnection();
			sql = "SELECT * FROM car ORDER BY num";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			System.out.println("==========");
			if (rs.next()) {
				System.out.println("번호\t자동차명\t가격\t제조사\t등록일");
				do {
					System.out.print(rs.getInt("num"));
					System.out.print("\t");
					System.out.print(rs.getString("name"));
					System.out.print("\t");
					System.out.print(rs.getInt("price"));
					System.out.print("\t");;
					System.out.print(rs.getString("maker"));
					System.out.print("\t");
					System.out.println(rs.getDate("reg_date"));
				}

				while(rs.next());
			}
			else {
				System.out.println("등록된 데이터가 없습니다.");
			}


		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBUtil.executeClose(rs, pstmt, conn);
		}


	}

	//자동차 상세 보기
	public void selectDetailCar(int num) {
		Connection conn = null;
		PreparedStatement pstmt= null;
		String sql = null;
		ResultSet rs = null;
		
		try {
			conn = DBUtil.getConnection();
			sql = "SELECT * FROM car WHERE num=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1,num);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				System.out.println("번호 : " + rs.getInt("num"));
				System.out.println("자동차명 : " +rs.getString("name"));
				System.out.println("자동차 번호 : " +rs.getString("cnumber"));
				System.out.println("자동차 색상 : " +rs.getString("color"));
				System.out.println("자동차 제조사 : " +rs.getString("maker"));
				System.out.println("자동차 가격 : " +rs.getInt("price"));
				System.out.println("등록일 : " +rs.getDate("reg_date"));
			}
			else {
				System.out.println("검색된 데이터가 없습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBUtil.executeClose(rs, pstmt, conn);
		}

	}

	//자동차 정보 수정하기
	public void updateCar(int num,String name, String cnumber, String color, String maker, int price) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = null;
		try {
			conn = DBUtil.getConnection();
			sql = "UPDATE car SET name=?, cnumber =? , color =? , maker = ?, price = ? WHERE num =?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, name);
			pstmt.setString(2, cnumber);
			pstmt.setString(3, color);
			pstmt.setString(4, maker);
			pstmt.setInt(5, price);
			pstmt.setInt(6, num);
			
			int count = pstmt.executeUpdate();
			System.out.println(count + "개 행의 정보를 수정했습니다.");
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBUtil.executeClose(null, pstmt, conn);
		}

	}

	//자동차 정보 삭제하기
	public void deleteCar(int num) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = null;
		try {
			conn = DBUtil.getConnection();
			sql = "DELETE FROM car WHERE num = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, num);
			
			int count = pstmt.executeUpdate();
			System.out.println(count + "개 행을 삭제했습니다.");
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			DBUtil.executeClose(null, pstmt, conn);
		}

	}

}

CarMain

package kr.s37.jdbc.car;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CarMain {
	private BufferedReader br;
	private CarDAO car;

	//생성자
	public CarMain() {

		try {
			br = new BufferedReader(new InputStreamReader(System.in));
			car = new CarDAO();

			//메뉴 호출하기
			callMenu();
		}catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(br != null) try {br.close();} catch(IOException e) {}
		}

	}


	//메뉴
	public void callMenu() throws IOException {
		while(true) {
			System.out.print("1. 자동차 정보 등록 | 2. 자동차 목록 보기 | 3. 자동차 상세 보기 | 4. 자동차 정보 수정 | 5. 자동차 정보 삭제 | 6. 종료 > ");
			try {
				int no = Integer.parseInt(br.readLine());
				if (no == 1) { // 자동차 정보 등록
					System.out.print("자동차명 : ");
					String name = br.readLine();
					System.out.print("자동차 번호 : ");
					String cnumber = br.readLine();
					System.out.print("자동차 색상 : ");
					String color = br.readLine();
					System.out.print("자동차 제조사 : ");
					String maker = br.readLine();
					System.out.print("자동차 가격 : ");
					int price = Integer.parseInt(br.readLine());
					
					car.insertCar(name, cnumber, color, maker, price);
				}
				else if(no == 2) {
					car.selectCar();
				}
				else if(no == 3) {
					System.out.print("선택한 자동차의 번호 : ");
					int num = Integer.parseInt(br.readLine());
					
					car.selectDetailCar(num);
				}
				else if(no == 4) {
					System.out.print("수정할 자동차의 번호 : ");
					int num = Integer.parseInt(br.readLine());
					car.selectDetailCar(num);
					System.out.println("==========");
					System.out.print("자동차명 : ");
					String name = br.readLine();
					System.out.print("자동차 번호 : ");
					String cnumber = br.readLine();
					System.out.print("자동차 색상 : ");
					String color = br.readLine();
					System.out.print("자동차 제조사 : ");
					String maker = br.readLine();
					System.out.print("자동차 가격 : ");
					int price = Integer.parseInt(br.readLine());
					
					car.updateCar(num, name, cnumber, color, maker, price);
				}
				else if(no == 5) {
					car.selectCar();
					
					System.out.println("삭제할 자동차의 번호 : ");
					int num = Integer.parseInt(br.readLine());
					
					car.deleteCar(num);
				}
				else if(no == 6) {
					System.out.println("프로그램을 종료합니다.");
					break;
				}
				else {
					System.out.println("잘못 입력하셨습니다.");
				}

			} catch(NumberFormatException e) {
				System.out.println("숫자만 입력 가능합니다.");
			}

		}

	}

	public static void main(String[] args) {
		new CarMain();
	}

}
profile
Lucky Things🍀

0개의 댓글