Monday, February 1, 2016

Batch

Batch:
For large amount of sql running in one time

Suggest using Statement, because PreparedStatement has limitation for big inputs, which may cause exceptions

Remember to setAutoCommit(false), then call commit() at the end

  
 DataSource ds = DBConnector.setupDataSource();
 try(
  Connection conn = ds.getConnection();
  Statement stmt = conn.createStatement();
 ){
  conn.setAutoCommit(false);
  long start = System.currentTimeMillis();
  for(int i=0;i<20000;i++){
   stmt.addBatch("INSERT INTO users(username,pwd,ts) values('a"+i+"','pass',now())");
  }
  stmt.executeBatch();
  conn.commit();
  long end = System.currentTimeMillis();
  System.out.println("Spend time:"+(end-start)+"ms"); //see how fast
 } catch (SQLException e) {
  Logger lgr = Logger.getLogger(SqlHelper.class);
  lgr.log(Level.WARNING,e.getMessage(),e);
 }

No comments:

Post a Comment