jdbc批量插入幾百萬數據

 插入大量數據:

1.jdbc

2.MyBatis的批量插入

3.調用存儲過程

  long start = System.currentTimeMillis();
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/springbatch", "root", "123456");
            connection.setAutoCommit(false);
            String sql = "insert into person(name,age,nation,address) VALUES(?,?,?,?)";
            PreparedStatement prepareStatement = connection.prepareStatement(sql);
            int batchSize=0;
            for (int i = 0; i < 1000000; i++) {
                prepareStatement.setString(1, "cat");
                prepareStatement.setString(2, "110");
                prepareStatement.setString(3, "China");
                prepareStatement.setString(4, "China");
                prepareStatement.addBatch();
                if(batchSize==10000){
                    prepareStatement.executeBatch();
                    connection.commit();
                    batchSize=0;
                    prepareStatement.clearBatch();
                }else {
                    batchSize=batchSize+1;
                }
            }
            if(batchSize>0){
                prepareStatement.executeBatch();
                connection.commit();
            }
            if (prepareStatement != null) {
                prepareStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
            long end = System.currentTimeMillis();
            long result=end - start;
            System.out.println("耗時:"+result + "");

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章