TIL6 - (JDBC)(오류) 드라이버 close()문제 및 드라이버 로직 리팩토리

김지인·2022년 7월 9일
0
post-thumbnail

오류 해결 시간 : 10분

close문제해결

드라이버를 메모리에 올려서 사용하고 그 자원을 다시 반환하는 작업을 해주고 싶었다.

Class.forName("driver");
con =DriverManager.getConnection(url, Id, pwd);
------
preparedStatement pst = con.prepareStatement(sql);
ResultSet rs = pst.executeUpdate();

or

Statement st = con.createStatement();
ResultSet rs = st.excuteQuerty;
------
.
.
.
rs.close();
pst.close() or st.close()
con.close();

보통 드라이버를 메모리에 올리고 일련의 과정을 거친 후 드라이버가 더이상 필요하지 않으면 자원을 반환하는 구조이다.

문제의 로직이었는데 이는 트라이 안에서 객체를 반환하려고 해서 catch문에 걸리지 않아 오류가 뜨고 있는 모습을 볼 수 있었다.

그래서 모든 예외를 캐치한 후 finally로 강제로 close하는 방법을 사용했다.

public class NoticeBoardDAOImpl implements NoticeBoardDAOService{

	
	Connection con; 
	PreparedStatement pst; 
	ResultSet rs;
	

	public NoticeBoardDAOImpl() {
		con=null; 
		pst =null; 
		rs = null;
	}

그리고 객체 생성때 기본적으로 null값을 둬서 필요할때만 사용하고 자원을 반환하는 형식으로 구성했다.

해결 !


드라이브 로직 리팩토리

public class NoticeBoardDAOClose {

	Connection con;
	PreparedStatement pst;
	ResultSet rs;
	
	public NoticeBoardDAOClose() {}
	
	public NoticeBoardDAOClose(Connection con, PreparedStatement pst) {
		this.con = con;
		this.pst = pst;
		
	}
	
	public NoticeBoardDAOClose(Connection con, PreparedStatement pst, ResultSet rs) {
		this.con = con;
		this.pst = pst;
		this.rs =rs;
		
	}
	
	public void JdbcClose(Connection con, PreparedStatement pst) {
		if (pst != null) try { pst.close(); } catch(SQLException e) {}
		if (con != null) try { con.close(); } catch(SQLException e) {}	
	
	}
	
	public void JdbcClose(Connection con, PreparedStatement pst, ResultSet rs) {
		if (rs != null) try { rs.close(); } catch(SQLException e) {}
		if (pst != null) try { pst.close(); } catch(SQLException e) {}
		if (con != null) try { con.close(); } catch(SQLException e) {}
			
	}


close하는 부분의 클래스를 따로 만들어서 적용시켯다.


TIL5 -(자바) enum switch문으로 리팩토리에서 Token형식으로 수정한 GetTokenOfLoginCheck함수

기존의 if를 돌리는 부분을 수정하려고 한다. 그리고 기존에는 비밀번호까지 체크했으나, 한번에 USERIDUSERPWD를 받아 SQL구문을 이용해 체크할 것이다.

  • SQL에서 USERIDUSERPWD를 받아와 한번에 체크
  • IF문을 돌아주는 함수를 따로 선언(GetTokenOfLoginCheckIfLogic())
  • ResultSet 객체를 넣어 Token형식으로 출력
  • (빨간색 별표 꼭 해서 자원반환)

해서 결론적으로 기존의 코드보다 매우 짧은 코드로 완성되었다.
리팩토리를 하면서 느끼는점은 앞으로도 코드를 작성할 때 확장성이나, 함수의 기능을 딱 하나만 사용하도록 생각하면서 작성해야겠다.

profile
에러가 세상에서 제일 좋아

0개의 댓글