리소스 반환을 하지 않으면, 리소스가 부족해서 오류가 발생할 수 있음
public void deleteAll() throws SQLException{
Connection c = dataSource.getConnection();
// ps 생성 && 실행
PreparedStatement ps = c.preparedstatement("delete from users");
ps.executeUpdate();
// 리소스 반환
ps.close();
c.close();
}
만약 코드 실행하는 과정에서 예외가 발생한다면, 리소스 반환을 하지 못할 수 있다.
—> 이를 위해서 코드를 수정해야 한다.
public void deleteAll() throws SQLException{
// Connection와 PreparedStatement가 제대로 생성되었는지 확인하기 위해 null로 둔다.
Connection c = null;
PreparedStatement ps = null;
// ps 생성 && 실행
try{
c = dataSource.getConnection();
PreparedStatement ps = c.preparedstatement("delete from users");
ps.executeUpdate();
}catch(SQLException e){
throw e;
}finally{
if(ps != null){ // ps가 생성된 경우 실행
try{
ps.close();
}catch(SQLException e){}//ps를 실행하는 중 예외가 발생했을 수 있으니 catch 해준다.
}
if(c != null){ // c가 생성된 경우 실행
try{
c.close();
}catch(SQLException e){}//c를 사용하는 중 예외가 발생했을 수 있으니 catch 해준다.
}
}
}