Oracle 공부 8일차 & JDBC 공부

mg·2025년 2월 12일

Oracle 공부

목록 보기
9/10
post-thumbnail

내용 요약

  • DBUtil.java 패키지
  • JDBC
    • preparedstatement
    • preparedstatement
    • CallableStatement
    • transaction(트랜잭션)
    • NOTE


DBUtil.java 패키지 생성

  • 1,2,5 단계는 중복되는 내용이기 때문에 util패키지의 메서드로 만들어 사용하도록 함.
public class DBUtil {
	private static final String DB_DRIVER = "oracle.jdbc.OracleDriver";
	private static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
	private static final String DB_ID = "user01";
	private static final String DB_PASSWORD = "1234";
	
	// Connection 객체를 생성해서 반환
	public static Connection getConnection() throws ClassNotFoundException,SQLException{
		
		// JDBC 수행 1단계 : 드라이버 로드
		Class.forName(DB_DRIVER);
		
		// JDBC 수행 2단계 : Connection 객체 생성		
		return DriverManager.getConnection(DB_URL,DB_ID,DB_PASSWORD);	
	}
	
	// 자원정리
	public static void executeClose(ResultSet rs,PreparedStatement pstmt,Connection conn) {
		if(rs!=null)try {rs.close();}catch(SQLException e) {}
		if(pstmt!=null)try {pstmt.close();}catch (SQLException e) {}
		if(conn!=null)try {conn.close();}catch (SQLException e) {}
	}
	
	public static void executeClose(CallableStatement cstmt, Connection conn) {
		if(cstmt!=null)try {cstmt.close();}catch (SQLException e) {}
		if(conn!=null)try {conn.close();}catch (SQLException e) {}
	}
}


실제로는 statement를 사용하지 않고 preparedstatement를 사용. (보안 등의 이유)

preparedstatement

SQL문 : Oracle SQL Developer에 입력. test2 테이블 생성

create table test2(
 id varchar2(10) primary key,
 name varchar2(30) not null,
 age number(3),
 reg_date date not null
);



InsertMain.java 클래스 생성 : Create

public class InsertMain {
	public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = null;
		
		try {
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			
			// SQL문 작성
			sql = "INSERT INTO test2 (id,name,age,reg_date) VALUES (?,?,?,SYSDATE)";
			
			// JDBC 수행 3단계 : PreparedStatement 객체 생성
			pstmt = conn.prepareStatement(sql);
			// ?에 데이터 바인딩
			pstmt.setString(1, "red"); // 1번 ?에 데이터 전달
			pstmt.setString(2, "박문수"); // 2번 ?에 데이터 전달
			pstmt.setInt(3, 40); // 3번 ?에 데이터 전달 - 따로 입력하기 때문에 보안에 강함
			
			// JDBC 수행 4단계 : SQL문을 실행해서 테이블에 행을 추가
			int count = pstmt.executeUpdate(); // [주의]여기 괄호에 sql 넣으면 안됨. 
            									  데이터 다 날라감 3단계에서 sql 넣어야함
			System.out.println(count + "개 행을 추가했습니다.");
			
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			// 자원정리
			DBUtil.executeClose(null, pstmt, conn);	
            // resultSet에 null을 넣으면 resultSet제외 나머지만 close함
		}	
	}
}



SelectMain.java 클래스 생성 : Read

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

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;

		try {
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			
			// SQL문 작성
			sql = "SELECT * FROM test2 ORDER BY reg_date DESC";
			
			// JDBC 수행 3단계 : PreparedStatement 객체 생성
			pstmt = conn.prepareStatement(sql);
			
			// JDBC 수행 4단계 : SQL문 실행해서 테이블에 반영하고 결과집합을 ResultSet에 담아서 반환
			rs = pstmt.executeQuery();
			System.out.println("ID\t이름\t나이\t등록일");

			while (rs.next()) {		// while문 : 커서(next가 커서를 옮김)
				System.out.print(rs.getString("id")); 
				System.out.print("\t");
				System.out.print(rs.getString("name"));
				System.out.print("\t");
				System.out.print(rs.getInt("age"));
				System.out.print("\t");
				// 날짜:연-월-일 형식으로 데이터 반환
//				System.out.println(rs.getDate("reg_date"));
				
				// 날짜:연-월-일 시:분:초 형식으로 데이터 반환
				System.out.println(rs.getString("reg_date"));
			}

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



UpdateMain.java 클래스 생성 : Update

public class UpdateMain {
	public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = null;
		try {
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			
			// SQL문 작성
			sql = "UPDATE test2 SET name=?,age=? WHERE id=?";
			
			// JDBC 수행 3단계
			pstmt = conn.prepareStatement(sql);
			// ?에 데이터 바인딩
			pstmt.setString(1, "강호동");
			pstmt.setInt(2, 40);
			pstmt.setString(3, "sky");
			
			// JDBC 수행 4단계
			int count = pstmt.executeUpdate();
			System.out.println(count + "개 행의 정보를 수정했습니다.");

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// JDBC 수행 5단계
			DBUtil.executeClose(null, pstmt, conn);
		}
	}
}



DeleteMain.java 클래스 생성 : Delete

public class DeleteMain {
	public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = null;
		try {
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			
			// SQL문 작성
			sql = "DELETE FROM test2 WHERE id=?"; // FROM 앞에 *안들어감
			
			// JDBC 수행 3단계 : PreparedStatement 객체 생성
			pstmt = conn.prepareStatement(sql);
			// ?에 데이터 바인딩
			pstmt.setString(1, "sky");
			
			// JDBC 수행 4단계 : SQL문을 실행해서 테이블의 행을 삭제
			int count = pstmt.executeUpdate();
			System.out.println(count + "개 행을 삭제했습니다.");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// JDBC 수행 5단계 : 자원정리
			DBUtil.executeClose(null, pstmt, conn);
		}
	}
}




preparedstatement

SQL문 : table3, sequence 생성

create table test3(
 num number primary key,
 title varchar2(60) not null,
 name varchar2(30) not null,
 memo varchar2(4000) not null,
 email varchar2(30),
 reg_date date not null
);
create sequence test3_seq;



InsertMain.java 클래스 생성 : Create

public class InsertMain {
	public static void main(String[] args) {
		BufferedReader br = null;
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = null;
		
		try {
			// 입력받음
			br = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("제목:");
			String title = br.readLine();
			
			System.out.print("이름:");
			String name = br.readLine();
			
			System.out.print("메모:");
			String memo = br.readLine();
			
			System.out.print("이메일:");
			String email = br.readLine();
			
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			
			// SQL문 작성
			sql = "INSERT INTO test3 (num,title,name,memo,email,reg_date) 
  				   VALUES (test3_seq.nextval,?,?,?,?,SYSDATE)";
			
			// JDBC 수행 3단계 :preparedStatement 객체 생성
			pstmt = conn.prepareStatement(sql);
			// ?에 데이터 바인딩
			pstmt.setString(1, title);
			pstmt.setString(2, name);
			pstmt.setString(3, memo);
			pstmt.setString(4, email);
			
			// JDBC 수행 4단계
			int count = pstmt.executeUpdate();
			System.out.println(count + "개의 행을 추가했습니다.");
			
		} catch (Exception e) {
		 	e.printStackTrace();
		} finally {
			// JDBC 수행 5단계 : 자원정리
			DBUtil.executeClose(null, pstmt, conn);
			if(br!=null)try {br.close();}catch(IOException e) {}
		}
	}
}



Select 3가지 방법

  1. while문
  2. if~else문
  3. if~else + do~while문

SelectListMain.java 클래스 생성 : Read

  • table에 있는 모든 리스트(항목) 출력
public class SelectListMain {
	public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		try {
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			
			// SQL문 작성
			sql = "SELECT * FROM test3 ORDER BY num DESC";
			
			// JDBC 수행 3단계 : PreparedStatement 객체 생성
			pstmt = conn.prepareStatement(sql);
			
			// JDBC 수행 4단계 : SQL문 실행 결과를 ResultSet에 담아 반환
			rs = pstmt.executeQuery();
			System.out.println("번호\t제목\t작성자\t등록일");					
			while(rs.next()) {
				System.out.print(rs.getInt("num"));
				System.out.print("\t");
				System.out.print(rs.getString("title"));
				System.out.print("\t");
				System.out.print(rs.getString("name"));
				System.out.print("\t");
				System.out.println(rs.getDate("reg_date"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.executeClose(rs, pstmt, conn);
		}
	}
}



SelectSearchMain.java 클래스 생성 : Read

  • 제목을 기준으로 검색 후 출력
  • if문 쓰면 do~while문 사용해야함
public class SelectSearchMain {
	public static void main(String[] args) {
		BufferedReader br = null;
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		try {
			br = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("제목 검색어:");
			String keyword = br.readLine();
			
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			
			// SQL문 작성
			sql = "SELECT * FROM test3 WHERE title LIKE '%' || ? || '%'";
			
			// JDBC 수행 3단계
			pstmt = conn.prepareStatement(sql);
			// ?에 데이터 바인딩
			pstmt.setString(1, keyword);
			
			// JDBC 수행 4단계 : SQL문 실행
			rs = pstmt.executeQuery();
			
			if(rs.next()) { // 행이 없을 경우 처리
				System.out.println("번호\t제목\t작성자\t등록일");
				do{											
					System.out.print(rs.getInt("num"));
					System.out.print("\t");
					System.out.print(rs.getString("title"));
					System.out.print("\t");
					System.out.print(rs.getString("name"));
					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);
			if(br!=null)try {br.close();}catch(IOException e) {}
		}
	}
}



SelectDetailMain.java 클래스 생성 : Read

public class SelectDetailMain {
	public static void main(String[] args) {
		BufferedReader br = null;
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		try {
			br = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("번호:");
			int num = Integer.parseInt(br.readLine()); // 입력받은 번호를 int로 변환
			
			System.out.println("-------------------------------");
			
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			
			// SQL문 작성
			sql = "SELECT * FROM test3 WHERE num=?";
			
			// JDBC 수행 3단계
			pstmt = conn.prepareStatement(sql);
			// ?에 데이터 바인딩
			pstmt.setInt(1, num);
			
			// JDBC 수행 4단계 : SQL문 실행
			rs = pstmt.executeQuery();
			System.out.println();
			if(rs.next()) {								// 명백히 값이 1개면 if가능
				System.out.println("번호 : " + rs.getInt("num"));
				System.out.println("제목 : " + rs.getString("title"));
				System.out.println("작성자 : " + rs.getString("name"));
				System.out.println("내용 : " + rs.getString("memo"));
				
				String email = rs.getString("email");
				if(email == null) email = ""; // 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);
			if(br!=null)try {br.close();}catch(IOException e) {}
		}
	}
}



UpdateMain.java 클래스 생성 : Update

public class UpdateMain {
	public static void main(String[] args) {
		BufferedReader br = null;
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = null;
		try {
			br = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("번호:");
			int num = Integer.parseInt(br.readLine());
			
			System.out.print("제목");
			String title = br.readLine();
			
			System.out.print("이름:");
			String name = br.readLine();

			System.out.print("메모:");
			String memo = br.readLine();
			
			System.out.print("이메일:");
			String email = br.readLine();
			
			System.out.println("------------------------");
			
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			
			System.out.println("test3 테이블에 데이터를 수정합니다.");
			
			// SQL문 작성
			sql = "UPDATE test3 SET title=?,name=?,memo=?,email=? WHERE num=?"; 
  												   // where절(unique값) 필수 !!!
			
			// JDBC 수행 3단계
			pstmt = conn.prepareStatement(sql);
			// ?에 데이터 바인딩
			pstmt.setString(1, title);
			pstmt.setString(2, name);
			pstmt.setString(3, memo);
			pstmt.setString(4, email);
			pstmt.setInt(5, num);
			
			// JDBC 수행 4단계
			int count = pstmt.executeUpdate();
			System.out.println(count + "개 행의 정보를 수정했습니다.");
			
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			// 자원정리
			DBUtil.executeClose(null, pstmt, conn);
			if(br!=null)try{br.close();}catch(IOException e) {}
		}
	}
}



DeleteMain.java 클래스 생성 : Delete

public class DeleteMain {
	public static void main(String[] args) {
		BufferedReader br = null;
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = null;
		try {
			br = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("번호:");
			int num = Integer.parseInt(br.readLine());
			
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			
			System.out.println("test3 테이블에 데이터를 삭제합니다.");
			
			// SQL문 작성
			sql = "DELETE FROM test3 WHERE num=?"; // where(unique값) 필수!!!
			// JDBC 수행 3단계
			pstmt = conn.prepareStatement(sql);
			// ?에 데이터 바인딩
			pstmt.setInt(1, num);
			
			// JDBC 수행 4단계 : SQL문 실행
			int count = pstmt.executeUpdate();
			System.out.println(count+"개 행을 삭제했습니다.");
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			// 자원정리
			DBUtil.executeClose(null, pstmt, conn);
			if(br!=null)try {br.close();}catch(IOException e) {}
		}
	}
}




CallableStatement

SQL문 작성 : salary table 생성 + 프로시저 생성

create table salary(
 name varchar2(10) primary key,
 pay number not null; 
); 

INSERT INTO salary VALUES ('SMITH',1000);
INSERT INTO salary VALUES ('PETER',2000);
INSERT INTO salary VALUES ('JOHN',3000);
COMMIT;	
  • COMMIT안하면 데이터 추가 적용 안됨
create or replace procedure adjust(n in varchar2,
								   rate in float)
is
 newpay float;
begin
 SELECT pay INTO newpay FROM salary WHERE name = n;
 newpay := newpay + newpay * rate;
 UPDATE salary SET pay = newpay WHERE name = n;
 COMMIT;
 
 exception when others then
  dbms_output.put_line('error');
  ROLLBACK;
end;



CallableStatementMain.java 클래스 생성

public class CallableStatementMain {
	public static void main(String[] args) {
		BufferedReader br = null;
		
		Connection conn = null;
		CallableStatement cstmt = null;
		String sql = null;
		try {
			br = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("이름(SMITH,PETER,JOHN):");
			String name = br.readLine();
			System.out.print("급여 인상률:");
			float rate = Float.parseFloat(br.readLine());
			
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			
			// 프로시저 호출 문장 작성
			sql = "{call adjust(?,?)}";
			
			// JDBC 수행 3단계
			cstmt = conn.prepareCall(sql);
			// ?에 데이터 할당
			cstmt.setString(1, name);
			cstmt.setFloat(2,rate);
			
			// JDBC 수행 4단계
			cstmt.executeUpdate();
			System.out.println("급여 정보를 수정했습니다.");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 자원정리
			DBUtil.executeClose(cstmt, conn);
			if(br!=null)try {br.close();}catch(IOException e) {}
		}
	}
}




transaction(트랜잭션)

  • 트랜잭션 : 여러 값을 동시에 바꿀 때 하나라도 false가 나오면 전체가 ROLLBACK 되도록 하는 작업(데이터 왜곡 제거)

  • table1 테이블 사용

  • 테스트 목적 상 ? 안쓰고 그냥 직접 입력

public class TransactionMain {
	public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement pstmt1 = null;
		PreparedStatement pstmt2 = null;
		PreparedStatement pstmt3 = null;
		String sql = null;
		try {
			conn = DBUtil.getConnection();
			
			// 트랜잭션을 수동 처리하기 위해 auto commit 해제
			conn.setAutoCommit(false);
			
			sql = "INSERT INTO test1 VALUES ('서울',500)"; 
			pstmt1 = conn.prepareStatement(sql);
			pstmt1.executeUpdate();
			
			sql = "INSERT INTO test1 VALUES ('부산',400)";
			pstmt2 = conn.prepareStatement(sql);
			pstmt2.executeUpdate();
			
			// 테스트용으로 오류가 있는 SQL문 사용
			sql = "INSERT INTO test1 VALUES ('제주',300"; 	// 오류나는 문장 입력
			pstmt3 = conn.prepareStatement(sql);
			pstmt3.executeUpdate();

			// 정상적으로 작업 완료되면 commit
			conn.commit();
			System.out.println("작업 완료!!");
			
		} catch (Exception e) {
			e.printStackTrace();
			// 예외가 발생했을 경우 rollback
			try {
				conn.rollback();
			} catch (SQLException se) {
				se.printStackTrace();
			}			
		} finally {
			// 자원정리
			DBUtil.executeClose(null, pstmt3, null);
			DBUtil.executeClose(null, pstmt2, null);
			DBUtil.executeClose(null, pstmt1, null);
		}
	}
}




NOTE

SQL문 : note 테이블, sequence 생성

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;



NoteMain.java 클래스 생성

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) {}
		}
	}
	
	// 메뉴
	private 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) {
					// 상세글보기
					// 목록에서 선택할 글번호를 확인
					note.selectInfo();
					
					System.out.print("선택한 글의 번호:");
					int num = Integer.parseInt(br.readLine());
					System.out.println("--------------------");
					
					note.selectDetailInfo(num);
				}
				
				else if(no==4) {
					// 글수정
					// 목록에서 선택할 글번호를 확인
					note.selectInfo();
					
					System.out.print("수정할 글의 번호:");
					int num = Integer.parseInt(br.readLine());
					// 전달한 번호로 레코드 존재 여부 체크
					// 1: 존재, 0: 미존재, -1: 오류
					int count = note.checkRecord(num);
					if(count == 1) {
						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(count == 0) {
						System.out.println("번호를 잘못 입력했습니다.");
					} else {
						System.out.println("정보 처리 중 오류 발생");
					}
					
				}
				
				else if(no==5) {
					// 글삭제
					note.selectInfo();
					
					System.out.print("삭제할 글의 번호:");
					int num = Integer.parseInt(br.readLine());
					
					// 전달한 번호로 레코드 존재 여부 체크
					int count = note.checkRecord(num);
					// 1:존재, 0:미존재, -1:오류
					if(count == 1) {
						note.deleteInfo(num);
					} else if (count == 0) {
						System.out.println("번호를 잘못 입력했습니다.");
					} else {
						System.out.println("정보 처리 중 오류 발생");
					}
				}
				
				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();
		
	}
}



DAO : Data Access Object

  • 데이터베이스의 데이터를 전문적으로 호출하고 제어하는 객체

NoteDAO.java 클래스 생성

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;
		int cnt = 0;
		
		try {
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			// SQL문 작성
			sql = "INSERT INTO note VALUES (note_seq.nextval,?,?,?,?,?,SYSDATE)";
			// JDBC 수행 3단계
			pstmt = conn.prepareStatement(sql);
			// ?에 데이터 바인딩
			pstmt.setString(++cnt, name);
			pstmt.setString(++cnt, passwd);
			pstmt.setString(++cnt, subject);
			pstmt.setString(++cnt, content);
			pstmt.setString(++cnt, email);
			
			// JDBC 수행 4단계
			int count = pstmt.executeUpdate();
			System.out.println(count + "개의 행을 삽입했습니다.");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 자원정리
			DBUtil.executeClose(null, pstmt, conn);
		}		
	} // insertInfo
	
	// 목록보기
	public void selectInfo() {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		try {
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			// SQL문 작성
			sql = "SELECT * FROM note ORDER BY num DESC";
			// JDBC 수행 3단계
			pstmt = conn.prepareStatement(sql);
			// JDBC 수행 4단계
			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());
	
			} else {
				System.out.println("표시할 데이터가 없습니다.");
			}
			
			System.out.println("--------------------------------");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 자원정리
			DBUtil.executeClose(rs, pstmt, conn);
		}
	} // selectInfo
	
	// 상세글보기
	public void selectDetailInfo(int num) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		try {
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			// SQL문 작성
			sql = "SELECT * FROM note WHERE num=?";
			// JDBC 수행 3단계
			pstmt = conn.prepareStatement(sql);
			// ?에 데이터 할당
			pstmt.setInt(1, num); // (num,num) 이면 오류 날 수 있어서 1로 고치기
			// JDBC 수행 4단계
			rs = pstmt.executeQuery();
			
			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 = "";
				
				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);
		}
	} // selectDetailInfo
	
	// 조회하는 레코드가 존재하는지 여부 체크
	public int checkRecord(int num) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		int count = 0;
		try {
			// JDBC 수행 1,2단계
			conn = DBUtil.getConnection();
			// SQL문 작성
			sql = "SELECT * FROM note WHERE num=?";
			// JDBC 수행 3단계
			pstmt = conn.prepareStatement(sql);
			// ? 에 데이터 바인딩
			pstmt.setInt(1, num); 	// ?가 1개는 1입력
			// JDBC 수행 4단계
			rs = pstmt.executeQuery();
			if(rs.next()) {
				count = 1; // 레코드가 존재할 때 1 저장.		초기화를 0으로 해놔서 else문 필요X
			}
		} catch (Exception e) {
			count = -1;
		} finally {
			// 자원정리
			DBUtil.executeClose(rs, pstmt, conn);
		}	
		return count;
	}
	
	// 글수정
	public void updateInfo(int num,String name,String passwd,String subject,String content,String email) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = null;
		int cnt = 0;
		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(++cnt, name);
			pstmt.setString(++cnt, passwd);
			pstmt.setString(++cnt, subject);
			pstmt.setString(++cnt, content);
			pstmt.setString(++cnt, email);
			pstmt.setInt(++cnt, num);
			// JDBC 수행 4단계
			int count = pstmt.executeUpdate();
			System.out.println(count + "개 행의 정보를 수정했습니다.");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.executeClose(null, pstmt, conn);
		}
	} // updateInfo
	
	// 글삭제
	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단계 : SQL문 실행
			int count = pstmt.executeUpdate();
			System.out.println(count+"개 행을 삭제했습니다.");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 자원정리
			DBUtil.executeClose(null, pstmt, conn);
		}
	} // deleteInfo
	
	// 종료
}

0개의 댓글