예외 상황에 대한 처리
정상적인 JDBC 코드의 흐름을 따르지 않고 중간에 어떤 이유로든 예외가 발생할 경우 사용한 리소스를 반드시 반환하도록 해야 한다.
public void deleteAll() throws SQLException{
Connection c = dataSource.getConnection();
// 예외 발생 시 바로 메소드 **실행 중단**
PreparedStatement ps = c.prepareStatement("delete from users");
ps.executeUpdate();
ps.close();
c.close();
}
메소드에서 사용하는 자원: Connection
, PreparedStatement
PreparedStatement
처리 중 예외 발생 시 바로 메소드를 나가게 된다.
→ Connection
과 PreparedStatement
의 close() 메소드가 실행되지 않아서 리소스가 반환되지 않을 수 있다.
서버에서 제한된 수의 DB 커넥션을 생성해 재사용 가능한 풀로 관리한다.
getConnection()
: DB 와 커넥션을 가져온다.
→ close()
: 재사용 가능한 상태로 리소스 반환
리소스 고갈 시 심각한 오류가 발생하고 서버가 중단될 수 있다.
Connection
과 PreparedStatement
는 보통 풀pool 방식으로 운영된다.
Connection
, Statement
) 를 만들어둔다리소스 사용 시 유의사항
public void deleteAll() throws SQLException {
Connection c = null;
PreparedStatement ps = null;
try {
c = dataSource.getConnection();
ps = c.prepareStatement("delete from users");
ps.executeUpdate();
} catch (SQLException e) {
throw e;
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
}
}
if (c != null){
try{
c.close();
} catch (SQLException e){
}
}
}
}