本人在项目中,需要一次向数据库中插入多条数据!
  我是用for循环插入的,感觉效率太慢,安全性太差!
  先求如何快速,批量,一次性插入到数据库多条数据!

解决方案 »

  1.   

    PreparedStatement.addBatch();......
    PreparedStatement.executeBatch();
      

  2.   

    正解,但要注意在一定次数(比如20+)的addBatch()后,就要马上executeBatch(),这样才能避免发生内存吃紧的情况。
      

  3.   

    看来插入的还真的挺多那就考虑用batch吧!还要注意定量flush一下减少内存占用。
      

  4.   

    PreparedStatement.addBatch(); ...... 
    PreparedStatement.executeBatch();一次最多不要超过50条:
    1.因为当你插入的时候 数据库已经锁定,然而如果你一次性插入太多会造成其他业务的等待。
    2.会造成内存的溢出
      

  5.   

    Class.forName("com.mysql.jdbc.Driver");   
    Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://" +   
            "localhost:3306/excel2mysql", "wanle", "wanle");   
    // 关闭事务自动提交   
    con.setAutoCommit(false);   
      
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SS");   
    TimeZone t = sdf.getTimeZone();   
    t.setRawOffset(0);   
    sdf.setTimeZone(t);   
    Long startTime = System.currentTimeMillis();   
      
    PreparedStatement pst = (PreparedStatement) con.prepareStatement("insert into test04 values (?,'中国')");   
    for (int i = 0; i < 10000; i++) {   
        pst.setInt(1, i);   
        // 把一个SQL命令加入命令列表   
        pst.addBatch();   
    }   
    // 执行批量更新   
    pst.executeBatch();   
    // 语句执行完毕,提交本事务   
    con.commit();   
      
    Long endTime = System.currentTimeMillis();   
    System.out.println("用时:" + sdf.format(new Date(endTime - startTime)));   
      
    pst.close();   
    con.close();