티스토리 뷰
try - with - resources문
- 자바7 버전에서 추가됨.
- 입출력 처리시 예외가 발생하는 경우 JVM이 자동으로 close()를 호출하여 자원을 반납시켜준다.
try - catch문을 이용한 예외 처리
public List<Role> getRoles(){
List<Role> list = new ArrayList<>();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("org.mariadb.jdbc.Driver");
conn = DriverManager.getConnection(dburl, dbUser, dbPasswd);
String sql = "SELECT description, role_id FROM role ORDER BY role_id DESC";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
int id = rs.getInt("role_id");
String description = rs.getString("description");
Role role = new Role(id, description);
list.add(role);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
try - with - resources문을 이용한 예외 처리
public List<Role> getRoles(){
List<Role> list = new ArrayList<>();
try {
Class.forName("org.mariadb.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String sql = "SELECT description, role_id FROM role ORDER BY role_id DESC";
try (
Connection conn = DriverManager.getConnection(dburl, dbUser, dbPasswd);
PreparedStatement ps = conn.prepareStatement(sql)
) {
try (
ResultSet rs = ps.executeQuery()
){
while(rs.next()) {
String description = rs.getString("description");
int id = rs.getInt("role_id");
Role role = new Role(id, description);
list.add(role);
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
참조
'Language > Java' 카테고리의 다른 글
Maven 프로젝트에서 Servlet 3.1로 업그레이드 하기 (0) | 2021.01.06 |
---|---|
Servlet 버전별 작성 방법 (0) | 2021.01.05 |
JDBC 설정 (0) | 2020.12.21 |
Maven 환경설정 (0) | 2020.12.21 |
redirect와 forward (0) | 2020.12.19 |
댓글