[DAO] DAO

zyan·2021년 9월 29일
0

Web

목록 보기
6/7

Data Access Object의 약자이며, sql + java, 즉 crud 메소드들로 구성된 클래스를 의미한다. db연동 클래스를 정형화하여 개발하게 하는 구조.

아래 코드와 같이 구성된 pattern을 DAO라 한다.

package step02.dao;

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

import org.junit.Test;

import util.DBUtil;

public class DeptDAO {
	
//@Test
public void deleteOne() {
	Connection con = null;
	Statement stmt = null;
		
	try {
		con = DBUtil.getConnection();
		stmt = con.createStatement();
			
		int result = stmt.executeUpdate("DELETE FROM dept WHERE deptno=60");
			
		if(result == 1) {
			System.out.println("삭제 성공");
		}else {
			System.out.println("deptno 삭제 실패");
		}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, stmt);
		}			
}
	
	
//@Test	
public void updateOne() {
	Connection con = null;
	Statement stmt = null;
		
	try {
		con = DBUtil.getConnection();
		stmt = con.createStatement();
			
		int result = stmt.executeUpdate("UPDATE dept SET loc='평양' WHERE deptno=60");
			
		if(result == 1) {
			System.out.println("수정 성공");
		}else {
			System.out.println("deptno 수정 실패");
		}
			
	} catch (SQLException e) {
		e.printStackTrace();
	} finally {
		DBUtil.close(con, stmt);
	}		
}
	
	
//@Test
public void insertOne() {
	Connection con = null;
	Statement stmt = null;
		
	try {
		con = DBUtil.getConnection();
		stmt = con.createStatement();
			
		//executeUpdate() : insert/update/delete sql문장 처리 메소드 
		int result = stmt.executeUpdate("insert into dept values (60, '교육부', '남부')");
			
		if(result == 1) {
			System.out.println("저장 성공");
		}else {
			System.out.println("deptno 중복 저장 불허");
		}
			
	} catch (SQLException e) {
		e.printStackTrace();
	} finally {
		DBUtil.close(con, stmt);
	}		
}
	
	
	
	
	
//부서번호(deptno)로 한 부서 정보만 검색
//@Test
public void selectOne() {
	Connection con = null;
	Statement stmt = null;
	ResultSet rset = null;
		
	try {
		con = DBUtil.getConnection();
		stmt = con.createStatement();
			
		rset = stmt.executeQuery("select * from dept where deptno=10");
			
		if(rset.next()) {
				System.out.println(rset.getInt("deptno") + "/" + rset.getString("dname") + "/" + rset.getString("loc"));
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, stmt, rset);
		}
}
	
	
//모든 검색
@Test
public void selectAll() {
	Connection con = null;
	Statement stmt = null;
	ResultSet rset = null;
		
	try {
		con = DBUtil.getConnection();  
		stmt = con.createStatement();   
			
		rset = stmt.executeQuery("select * from dept");
			
		while(rset.next()) {
				System.out.println(rset.getInt("deptno") + "/" + rset.getString("dname") + "/" + rset.getString("loc"));
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, stmt, rset);
		}
	}

}

0개의 댓글