티스토리 뷰

자바(Java)

addBatch executeBatch

xemaker 2017. 8. 31. 15:13

executeUpdate 로 쿼리를 실행했었는데 아시다 시피 건수가 많은 경우 오래 걸린다.


그래서 addBatch로 변경하려고 했다.


그런데 삽질을 좀 했다.. 이유가 뭐냐면..


기존에 쿼리 한개씩 실행하는 executeUpdate로 되어 있는 소스를 addBatch로 변경하려고 했다. (그냥 addBatch로 새로 개발했으면 이런 삽질은 없었을텐데..)


그런데 자꾸 1줄만 insert가 되는 것이였다.. 왜그러나 봤더니..


과거 executeUpdate 일 경우에는 prepareStatement가 많으면 에러가 났었다. 그래서


if(pstmt!=null) try{pstmt.close();}catch(SQLException e){};


이 코드를 넣었는데 이 코드 삭제를 하지 않았던 것이다.. 그래서 1줄만 insert가 되는 겨었다.


이제 본론으로 들어가면..

try{

String inSql=" INSERT INTO AA (a,b) VALUES(?,?) ";


BufferedReader in = new BufferedReader(new FileReader(pathFile));

int i=1; //0으로 하면 i%10000 == 이 처음 실행되기 때문에 1로 한다.

conn.setAutoCommit(false);

pstmt=conn.prepareStatement(insSql);

while((s=in.readLine())!=null){

  pstmt.setString(1,"");

  pstmt.setString(2,"");

  pstmt.addBatch();


//계속 추가하면 outOfMemory 에러가 나기 때문에 10000개씩 executeBatch() 해줌. 

 if((i%10000)==0){

    pstmt.executeBatch();

    pstmt.clearParameters();

    pstmt.clearBatch();

  }

}

int[] rr=pstmt.executeBatch();

System.out.println("결과="+rr[0]);

conn.commit();


in.close();


}catch(Exception e){

conn.rollback();

}finnally{

if(stmt!=null) try{stmt.close();}catch(SQLException e){};

if(pstmt!=null) try{pstmt.close();}catch(SQLException e){};

if(conn!=null) try{conn.close();}catch(SQLException e){};

}


근데 conn.commit()을 안해도 테이블에 데이타가 들어갔다..





댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함