java 批量添加实例

最近由于工作需要 需要做一个生成海量数据的程序!开始分析这个问题 最终总结如下:

方案一 用jdbc 的API 那么这种方法的效率应该是最高的!

方案二 用hibernate 的API 这个方案比第一种方案的效率低!

我开始很犹豫到底用那一种呢!由于我们的项目使用SSH框架的!如果用单纯的JDBC API 那么还要在连接一次数据库

显然是不可取的!【减少socket通讯可以提高系统性能】

如果单纯的用hibernate 的API 效率太低! 所以我最终选择的方案是二者结合!

干脆吧 这个方法放到hibernate 自动生成的dao里面

OK 首先把你的方法也放到Hibernate生成的dao里面 为什么 原因是用 this.getSession().connection();可以得到连接

Connection conn= this.getSession().connection(); [注意connection()这个方法已经过时]

conn.setAutoCommit(false);//自动提交事物设置为false 不自动提交

String sql = "insert into test(username,userpwd) values(?,?)";

PreparedStatement pstmt = conn.prepareStatement(sql);//创建PreparedStatement 对象

for (int index = 0; index < number; index++) {

   pstmt.setString(1,"username");

   pstmt.setString(2,"userPwd");
   // 将一组对象添加到prepareStatement对象的批处理密令中
    pstmt.addBatch();

   //每5000条进行事物提交
    if (index%5000==0) {
     pstmt.executeBatch(); //执行prepareStatement对象中所有的sql语句
     conn.commit();//事物提交
     this.getSession().flush();//数据库与缓存同步
     this.getSession().clear();//清空缓存
     if (null==conn) { //如果连接关闭了 就在创建一个 为什么要这样 原因是 conn.commit()后可能conn被关闭
      conn = this.getSession().connection();
     }
    }
   }

   pstmt.executeBatch();//1.执行与5000去摸不是0的数据

   conn.commit();//事物提交
   conn.close();//释放连接
   pstmt.close();//释放资源

 

  我以上用的都是PreparedStatement 如果要用Statement 可以改成下面的

 

Connection conn= this.getSession().connection(); [注意connection()这个方法已经过时]

conn.setAutoCommit(false);//自动提交事物设置为false 不自动提交 

Statement st=conn.createStatement();

for (int index = 0; index < number; index++) {

      // 将一组对象添加到Statement对象的批处理密令中

     st.addBatch("insert into test(username,userpwd) values('"+username+"','"+userpwd+"')");

   //每5000条进行事物提交
    if (index%5000==0) {
     st.executeBatch(); //执行prepareStatement对象中所有的sql语句
     conn.commit();//事物提交
     this.getSession().flush();//数据库与缓存同步
     this.getSession().clear();//清空缓存
     if (null==conn) { //如果连接关闭了 就在创建一个 为为什么要这样 原因是 conn.commit()后可能conn被关闭
      conn = this.getSession().connection();
     }
    }
   }

   st.executeBatch();//1.执行与5000去摸不是0的数据

   conn.commit();//事物提交
   conn.close();//释放连接
   st.close();//释放资源

注意Statement与 PreparedStatement在进行批处理时候唯一的不同家就是:addBatch();方法是否传递参数

从效率已经占用内存的多少上 我还是推荐大家使用PreparedStatement

 

说明:由于对公司信息的保护 以上是程序的最简单版本!其他重要数据已经修改!测试时候一次可以插入50万条数据!在大的没有测过!此时服务器还可以继续进行其他的操作!

 

你可能感兴趣的:(数据连接类)