MySQL的批量操作

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;


public class TestJdbc_fatch {

 String url = "jdbc:mysql://localhost:3306/test";
 String username ="root";
 String password = "root";
 Connection conn = null;
 PreparedStatement pstmt = null;
 public void con(){
  try {
   Class.forName("com.mysql.jdbc.Driver");
   conn = DriverManager.getConnection(url,username,password);
   conn.setAutoCommit(false);
   String sql = "insert into admin(username,password)values('ss','123')";
   pstmt = conn.prepareStatement(sql);
   for(int i=0;i<5;i++){
   pstmt.addBatch();
   }
   pstmt.executeBatch();
   conn.commit();
   
  } catch (Exception e) {
   try {
    conn.rollback();
   } catch (SQLException e1) {
    e1.printStackTrace();
   }
   e.printStackTrace();
  }finally{
   try {
    pstmt.close();
    conn.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
   pstmt = null;
   conn = null;
  }
  
  
 }
 public static void main(String[] args) {
  new TestJdbc_fatch().con();
 }
}

 

最近用mysql用的有点烦,MySQL驱动JDBC支持批量操作,我简单的测试了一下,这是我写的一个测试程序!说实话addBatch就相当于将sql保存至列表中,executeBatch没有加rewriteBatchedStatements=true参数时,executeBatch还是将列表中的sql一条一条executeUpdate,当连接MySQL的url设置了rewriteBatchedStatements=true参数时,则会返回executeBatchedInserts(batchTimeout);而在此方法中,sql会编译成批量插入的形式处理,而如果没有加rewriteBatchedStatements=true,则会返回executeBatchSerially(batchTimeout);而在此方法中,是将此列表循环一条一条的executeUpdate。

我这个也是参考了一下这个哥们的博文,http://www.cnblogs.com/liangge0218/archive/2011/07/02/2096458.html

这哥们确实测试过了,我也测试了一下,确实是这样的!

posted on 2012-01-03 15:56  神化  阅读(503)  评论(0编辑  收藏  举报