Java批量插入数据1秒插入10W条

@RequestMapping(value = "/sql/test", method = {RequestMethod.GET, RequestMethod.POST})
public MyResult sqltst() {
    Connection conn = null;
    Long begin = new Date().getTime();

    try {
        conn =  DriverManager.getConnection("jdbc:mysql://ipp:3306/数据库名", "账户", "密码");//获取连接
        if(conn != null){
            System.out.println("获取连接成功");
        }else{
            System.out.println("获取连接失败");
        }

        conn.setAutoCommit(false);
        PreparedStatement pst = conn.prepareStatement("");
        // sql前缀
        String prefix = "INSERT INTO test (name) VALUES ";  //此处为对应插入表的列
        // 保存sql后缀
        StringBuffer suffix = new StringBuffer();
        for(int i = 0;i<100000;i++){
            suffix.append("( "+Math.random()*100000+"),");   //拼接sql
        }
        String sql = prefix + suffix.substring(0, suffix.length() - 1);
        
        pst.addBatch(sql);
        pst.executeBatch();
        conn.commit();
        pst.close();
        conn.close();

    }catch (Exception e){
        e.printStackTrace();
    }
    // 结束时间
    Long end = new Date().getTime();
    // 耗时
    System.out.println("10万条数据插入花费时间 : " + (end - begin) / 1000 + " s");
    MyResult myResult = new MyResult();
    return myResult;
}

 

 

10万条数据插入花费时间 : 1 s

 

具体会根据表大小,计算机配置耗时不同

你可能感兴趣的:(Java批量插入数据1秒插入10W条)