-
카테고리
-
세부 분야
백엔드
-
해결 여부
미해결
Connection, pstmt 질문입니다
23.04.11 16:52 작성 23.04.11 16:52 수정 조회수 292
0
public void aaa() throws SQLException {
String sql = "delete from member where member_id =?";
String memberId = "!";
try {
Connection con = getConnection();
PreparedStatement pstmt = null;
pstmt = con.prepareStatement(sql);
} catch (Exception e) {
}
}
이렇게 try 문 안에서 한번에 받지 않고
Connection con = null;
PreparedStatement pstmt = null;
이렇게 null로 외부에서 선언을 하는 것은 finally 문 안에 close 메서드에 파라미터로 넘겨주기 위함이 맞나요 ?
답변을 작성해보세요.
4
hjoo
2023.04.11
맞아요! 코드에서 Connection
과 PreparedStatement
를 외부에서 null로 선언하고 있는 이유는, 주로 다음과 같은 상황 때문이에요.
try
블록 안에서 발생하는 예외를 처리하면서,catch
블록에서도 이 변수들에 접근할 수 있어요.finally
블록에서 이 변수들을 사용해 자원을 안전하게 닫아주기 위해서예요.finally
블록은 예외가 발생하든 안 하든 실행되기 때문에, 이렇게 하면 코드가 깔끔하게 정리돼요.
finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
// 예외 처리
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// 예외 처리
}
}
}
이렇게 하면 코드가 더 안전하고 깔끔해져요!
답변 2