부자 되기 위한 블로그, 머니킹

최근 개발 생산성을 높이기 위한 Dummy Create Module을 개발하고 있다. 항상 DB와 Spring을 연동할 때는 JPA를 써왔지만 아무래도 Dummy Create의 호환성을 위해 JDBC로 개발하기로 마음먹었다. 오늘부터 해당 JDBC 부분에 대한 기능 및 DB 접근 방법에 대해 포스팅할 생각이다. 오늘은 Table이 존재하는지 확인하는 Method를 소개할 까 한다.

JDBC로 DB 연결 

implementation 'org.springframework.boot:spring-boot-starter-jdbc'

gradle에 다음과 같이 의존성을 추가해주어야 한다.

 

 

Connection con = null;

try {
    // db 연결 설정
    Class.forName("org.h2.Driver");
    String url = "url";
    String id = "id";
    String pw = "password";
    System.out.println("DB정상연결");
    
    try {
        // db 연결
        con = DriverManager.getConnection(url, id, pw);
        DatabaseMetaData dbmd = con.getMetaData();
        String tableName = "BOARD";

        // 테이블 존재하는지 확인
        ResultSet tableRs = isTableExist(dbmd, tableName);

        if(!tableRs.next()) throw new SQLException();
        
     } catch (SQLException e) {
                System.out.println("DB계정불일치");
                e.printStackTrace();
    }
} catch (ClassNotFoundException e) {
    System.out.println("DB연결실패");
    e.printStackTrace();
}

DB 기본 연결 로직이다. Connection 객체를 통해 연결 정보를 파라미터로 넣어 연결한다. 기본적으로 모든 DB 작업은 DatabaseMetaData를 통해 이루어진다. 그리고 그 결과는 ResultSet을 통해 받는다.

 

테이블 존재 여부 확인은 isTableExists로 함수화 시켰다.

 

 

테이블 존재 여부 확인 메소드

private static ResultSet isTableExist(DatabaseMetaData dbmd, String tableName) throws SQLException {
    ResultSet rs = dbmd.getTables(null, "PUBLIC", tableName, null);
    //while(rs.next()) {
    //    String table = rs.getString("TABLE_NAME");
    //    System.out.println("Table Name : " + table);
    //}
    return rs;
}

 

getTables 메소드를 통해 table을 찾을 수 있다. 기본적으로 ResultSet에는 여러값들이 저장되며 next() 메소드를 통해 하나하나씩 꺼낼 수 있다. 해당 ResultSet을 반환한 후에 rs.next()가 있는지 없는지를 확인하여 검출한다