상세 컨텐츠

본문 제목

[3.1] 다시 보는 초난감DAO

토비의스프링

by kwanghyup 2020. 10. 28. 18:26

본문

DB커넥션이라는 제한적인 리소스를 공유해 사용하는 서버에서

동작하는 JDBC코드는 반드시 예외처리를 해주어야 한다.

 

JDBC수정 기능의 예외처리 코드 

 

UserDaoTest의 delteAll()메소드를 보자.

public void deleteAll() throws SQLException {
	Connection c = dataSource.getConnection();
	
	//(s) 여기서 예외가 발생하면 메소드 실행이 중단된다. 
	String sql = "truncate users";
	PreparedStatement ps = c.prepareStatement(sql);
	ps.executeUpdate(); 
	//(e)
	
	ps.close();
	c.close();
}

이 메소드는 PreparedStatement와 Connection이라는

두 개의 공유 리소스를 사용하고 있다.

 

만약 PreparedStatement를 처리하는 과정에서 예외가 발생한다면

close()메소드가 실행되지 않아 리소스가 반환되지 않을 것이다.

 

그래서 JDBC 코드에서는 어떤 상황에서도 가져온 리소스를 반환하도록

try/catch/finally구문을 사용하고 있다.

 

이를 deleteAll()메소드에 적용해보자.

public void deleteAll() throws SQLException {
	
	Connection c = null;
	PreparedStatement ps = null;
	
	try { // 예외 발생한 가능성이 있는 코드를 모두 try블록으로 묶어준다. 
		c = dataSource.getConnection();
		String sql = "truncate users";
		ps = c.prepareStatement(sql);
		ps.executeUpdate();
	} catch (SQLException e) {
		throw e; 
	} finally {
		
		if(ps!=null) {
			try {
				ps.close();
			} catch (SQLException e) {
				// ps.close() 메서드에서도 SQLException 예외가 발생할 수 있다.  
			}
		}
		
		if(c!=null) {
			try {
				c.close();
			} catch (SQLException e) {
				// ps.close() 메서드에서도 SQLException 예외가 발생할 수 있다.
			}
		}
		
	}		
}

 

JDBC 조회기능의 예외처리 

 

JDBC 예외처리를 적용한 getCount()메소드

public int getCount() throws SQLException {
	
	Connection c = null;
	PreparedStatement ps =null;
	ResultSet rs = null; 
	
	try {
		c = dataSource.getConnection();
		
		String sql = "select count(*) from users";
		ps = c.prepareStatement(sql);
		
		rs = ps.executeQuery();
		rs.next();
		int count = rs.getInt(1);
		return count;
	} catch (Exception e) {
		throw e;
	} finally {
		
		if(rs!=null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// 예외처리
			}
		}
		
		if(ps!=null) {
			try {
				ps.close();
			} catch (SQLException e) {
				// 예외처리    
			}
		}
		
		if(c!=null) {
			try {
				c.close();
			} catch (SQLException e) {
				// 예외처리
			}
		}			
	} // e: finally
	 
} // e : getCount()

 

 

관련글 더보기

댓글 영역