原生jdbc批量操作,批量添加

原生jdbc批量操作,批量添加

在写一个批量添加,本来是用的hibernate为基础的JPA,可是在批量添加时效率太低了,我计算了一下,插入500条数据使用了6秒,后来我改用了原生的没有封装的jdbc去写批量添加时,插入2000条根本感觉不到延迟,比封装过的好了不知道多少。
上代码:


    /**
     * 原生sql执行
     * @param stuNum 待生成的数据个数
     */
    private void saveBetchSql(int stuNum, String name) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb" +
                    "?useUnicode=true&characterEncoding=UTF-8&useServerPrepStmts=false&rewriteBatchedStatements=true","root","root");
            connection.setAutoCommit(false); //设置手动提交
            //预编译sql对象,只编译一回
            PreparedStatement ps = connection.prepareStatement(
                    "insert into tb_user (name) values(?)");
            for (int i = 0; i < stuNum; i++) {
                ps.setString(1,name);
                ps.addBatch();//添加到批次
            }
            ps.executeBatch();//提交批处理
            connection.commit();//执行
            connection.close();
        } catch (ClassNotFoundException e) {
            log.info("驱动错误");
            e.printStackTrace();
        } catch (SQLException e) {
            log.info("连接数据库失败");
            e.printStackTrace();
        }

    }

猜你喜欢

转载自blog.csdn.net/zhangjingao/article/details/80331415