现在的位置: 首页 > 综合 > 正文

java 批量添加数据

2018年05月22日 ⁄ 综合 ⁄ 共 1435字 ⁄ 字号 评论关闭

一次添加一条数据;很简单,一个真实需求:一次添加140000行数据,就不是那么简单了;注意此时Hibernate 已经效率很低了。还是最原始的操作:

 

Connection con = null;
  try {
    con = this.getCommonDAOHibImpl().getConnection();
    con.setAutoCommit(false);
    PreparedStatement pstm = null; 
    String sql = "insert 表名"  +
     "(列1,列2,.......) " +
     "values( ?, ?, ?, ?, ? , ?, ?, ?, ?, ?,?,?)";
    pstm  = con.prepareStatement(sql);
    
    //执行保存到数据库
    for(int i=0; i<msg.length; i++)
    {
     UmsSubmit mobile = new UmsSubmit();
     mobile.setClientId(item.getClientId());
     mobile.setSrcTerminalId(item.getSrcTerminalId());
     mobile.setAgentCode(item.getAgentCode());

     .........
     for (String tel : list)
     {
      mobile.setDestTerminalId(tel);
      
      pstm.setInt(1, mobile.getChannel());
      pstm.setInt(2, mobile.getMsgLevel());
      pstm.setString(3, mobile.getMsgSrc());
      pstm.setString(4, mobile.getSrcTerminalId());
      pstm.setString(5, mobile.getDestTerminalId());
      pstm.setBytes(6, mobile.getMsgContent());
      pstm.setString(7, mobile.getTransactionFlag());
      pstm.setTimestamp(8, mobile.getSendTime());
      pstm.setTimestamp(9, mobile.getRequestTime());
      pstm.setString(10, mobile.getClientId());
      pstm.setString(11, mobile.getAgentCode());
      pstm.setString(12, "成功");
      
      pstm.addBatch();
      points++;
     }//for循环结束
     pstm.executeBatch();
    con.commit();
    }//循环消息数组结束 
  } catch (Exception e) {
   e.printStackTrace();
   try { con.rollback(); } catch (SQLException e1) {e1.printStackTrace(); }
  }

抱歉!评论已关闭.