JDBC快速保存数据到MySQL

来源:互联网 发布:大数据细分领域 编辑:程序博客网 时间:2024/06/01 18:46

摘要:笔者需求是1秒保存2万条以上的数据到MySQL,用mybatis批量添加测试没有达到,下面这种差不多
测试准备100万条左右,时间是字符串类型的

    @Test    public  void insert() {        // 开时时间        Long begin = System.currentTimeMillis();        try {            Class.forName("com.mysql.jdbc.Driver");            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yfaf", "root", "abcdef");            DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");        String time= LocalDateTime.now().format(format);            StringBuffer suffix = new StringBuffer();            // 设置事务为非自动提交            conn.setAutoCommit(false);            PreparedStatement pst = conn.prepareStatement("");            // 构建sql前缀            String prefix = "insert into realtime_data(time,data,index_id,department_id) values ";            // 外层循环,总提交事务次数            for (int i = 1; i <= 100; i++) {                for (int j = 1; j <= 10000; j++) {                    // 构建sql后缀                    suffix.append("("+"\""+ time+ "\"" + ","+ 1.0f +"," + 7201+ "," + 4 +"),");                }                // 构建完整sql                String sql = prefix+(suffix.substring(0, suffix.length()-1));                pst.addBatch(sql); // 添加执行sql                pst.executeBatch();  // 执行操作                conn.commit();     // 提交事务                suffix.setLength(0);  // 清空上一次添加的数据            }            // 头等连接            pst.close();            conn.close();        } catch (Exception e) {            e.printStackTrace();        }        // 结束时间        Long end =System.currentTimeMillis();        // 耗时        System.out.println("time : " + (end - begin) / 1000 + " s");    }

经测试,每次保存差不多42,43秒左右,但是,有的说这种方式测试100万条添加只需23秒左右!我换了3台电脑测试的,都是42秒左右!!不只哪里的原因,有测试到20几秒的望告知

原创粉丝点击