1 분 소요

5. JDBC


: 기존 JDBC 실습과 비슷한 작업

1) 반복해서 사용하는 값이나 메서드 처리

  • DB파일의 위치를 가져오는 경우
    • 메서드 별로 모든 DB위치를 적어주다보니 유지보수와 개발이 어려웠음. 이에 필드로 변수값을 빼고 final로 선언하여 수정이 불가하도록 함.
    • 단, 접근해야할 DB가 조금씩 다르므로 DB명을 변수명에 포함시켜 작성.
    • 프로젝트 파일 위치는 getAbsolutePath() 메서드로 작성함.
  • GETTER, SETTER, CONSTRUCTOR 등의 메서드 생성
    • lombok이라는 라이브러리를 나중에 알게 됨.
    • 어노테이션으로 해당작업을 대체해줄 수 있음.

2) DB Insert 효율화

  • API에서 가져온 데이터 양이 17,000개가 넘는 상황. row데이터를 하나씩 받아올때마다 DB에 가서 insert를 하고 오기에는 자료가 너무 많아 소모되는 리소스가 많음. (무척 느림)
  • Connection 객체를 사용해도 느림.

- addBatch

  • PreparedStatement 라이브러리에서 제공하는 기능.

  • 쿼리를 메모리에 올려두었다가 한번에 insert 처리가 가능. (addBatch() -> executeBatch())

  • 단, 너무 많은 양을 메모리에 올려두었다 처리하면 오히려 속도 저하 가능성도 있음. 따라서 적당히 덩어리 처리를 하는 것이 효율적일 수 있음.

    public void insertWifiInfoToTableBatch(List<Data> list, int batchCnt, int totalDataCnt) {
    	Connection connection = null;
    	PreparedStatement preparedStatement = null;
    	ResultSet rs = null;
    		// 1. 드라이버 로드
    	try {
    		Class.forName("org.sqlite.JDBC");
    	} catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
      
        // 2. 커넥션 객체 생성
        try {
            connection = DriverManager.getConnection("jdbc:sqlite:" + getAbsolutePath() + ListDbFile);
      
            String sql = " insert into " + ListDbTable
                + " (controlNum, jachigu, wifiName, roadAddress, detailAddress, installLocation, installType, installOrg, serviceType, webType, installYear, inAndOut, wifiProp, LAT, LNT, workDate) "
                + " values "
                + " (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); ";
            connection.setAutoCommit(false); // 오토커밋 끄기 (이래야 batch가 제대로 실행됨)
            preparedStatement = connection.prepareStatement(sql);
      
            for(Data item : list) {
                preparedStatement.setString(1, item.getX_SWIFI_MGR_NO());
                preparedStatement.setString(2, item.getX_SWIFI_WRDOFC());
                preparedStatement.setString(3, item.getX_SWIFI_MAIN_NM());
                preparedStatement.setString(4, item.getX_SWIFI_ADRES1());
                preparedStatement.setString(5, item.getX_SWIFI_ADRES2());
                preparedStatement.setString(6, item.getX_SWIFI_INSTL_FLOOR());
                preparedStatement.setString(7, item.getX_SWIFI_INSTL_TY());
                preparedStatement.setString(8, item.getX_SWIFI_INSTL_MBY());
                preparedStatement.setString(9, item.getX_SWIFI_SVC_SE());
                preparedStatement.setString(10, item.getX_SWIFI_CMCWR());
                preparedStatement.setString(11, item.getX_SWIFI_CNSTC_YEAR());
                preparedStatement.setString(12, item.getX_SWIFI_INOUT_DOOR());
                preparedStatement.setString(13, item.getX_SWIFI_REMARS3());
                preparedStatement.setString(14, item.getLNT());
                preparedStatement.setString(15, item.getLAT());
                preparedStatement.setString(16, item.getWORK_DTTM());
      
                preparedStatement.addBatch(); // 배치에 넣어놓기
                batchCnt++;
            }
            preparedStatement.executeBatch(); // 배치 실행
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 6. 객체 연결 해제(close)
            try {
                if (rs != null && !rs.isClosed()) {
                    rs.close();
                }
            } catch(SQLException e){
                e.printStackTrace();
            }
      
            try {
                if (preparedStatement != null && !preparedStatement.isClosed()) {
                    preparedStatement.close();
                }
            } catch(SQLException e){
                e.printStackTrace();
            }
      
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch(SQLException e){
                e.printStackTrace();
            }
        }
    
    • 실제 소요시간

    before-batch(batch작업 전 112ms 소요)

    after-batch-allinone(batch작업 후 80ms 소요)

addbatch_autocommit_false(autocommit작업 후 6ms 소요)


마지막 수정일시: 2022-08-09 01:30

댓글남기기