Java實現批量插入


//方法執行的開始時間

long startTime = System.currentTimeMillis();

Connection conn = null;

try{

  //獲取連接

  conn = getConnection();

  //設置不自動提交

  conn.setAutoCommit(false);

  //准備執行的SQL

  PreparedStatement stmt = conn.prepareStatement("INSERT INTO student_tmp VALUES (?,?,?)");

  //循環插入100萬條數據

  for (int i = 0; i < 1000000; i++){

    stmt.setInt( 1,  i );

    stmt.setString( 2,  "小明" + i );

    stmt.setString( 3,  i + "班")

    if(  i/100000 == 0 ){

      //每10萬條數據提交一次

      stmt.executeBatch();

      conn.commit();

    }

    //提交最后一次的數據,防止有數據未提交

    stmt.executeBatch();

    conn.commit();

} catch (Exception e) {

  //出現異常回滾事務

  conn.rollback();

  e.printStackTrace();

}  finnally {

  //斷開連接

  conn.close();

  //方法執行的結束時間

  long endTime = System.currentTimeMillis();

  System.out.println("方法執行的時間:" + (endTime - startTime) + "ms" );

}

      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM