본문 바로가기
Front-end/JSP

[에러해결] JSP - com.mysql.cj.exceptions.StatementIsClosedException

by whatamigonnabe 2022. 5. 9.

DB를 연동해서 사용할 때, 닫은 connection 객체를 다시 사용하면 발생하는 현상이다.

나의 경우, 데이터 접근 객체(DAO)에서 클래스 정의 맨 앞에 connection객체를  만들어 놓고,

모든 함수 마지막에서 닫았다. 객체 생성은 한번 해놓고 여러번 닫으니 에러가 발생할 수 밖에;;

이를 해결하기 위해 찾아보니 항상 모든 연결을 닫아주어야 에러도 줄고 데이터 누수도 막을 수 있다고 한다

그래서 dao 객체 안의 함수 마다 db에 연결 후 try catch finally를 이용해 db연결을 닫아주었다.

public String getDate() {
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Connection conn = null;
		String dbURL = "jdbc:mysql://localhost:3306/FLYING";
		String dbID = "root";
		String dbPW = "12345678";
		String SQL = "SELECT NOW()";
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			conn = DriverManager.getConnection(dbURL, dbID, dbPW);
			pstmt = conn.prepareStatement(SQL);
			rs = pstmt.executeQuery();
			if(rs.next()) {
				return rs.getString(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(pstmt != null) {
				try {
					pstmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return ""; //database error
	}