java快速插入100万条数据

怎么给一张表插入100万条数据,如果用for循环那low暴了,有得等。

 借鉴博客:https://blog.csdn.net/gzt19881123/article/details/122815596

 

 

 

 

 

解决办法:

  1、开启mybatis的batch模式:application.yml文件配置

mybatis:
  executor-type: batch

 

  2、使用原生的jdbc

复制代码
    // 从spring管理的数据源中直接拿
    @Resource(name = "dataSource")
    private DataSource dataSource;
    
    @Test
    public void jdbcTest() throws SQLException {
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        String sql = "INSERT INTO tpm_user (id,name,createDate,remark) VALUES(?,?,?,?) ";

        PreparedStatement statement = connection.prepareStatement(sql);
        for (int i = 0; i < 1000000; i++) {
            statement.setLong(1, snowflakeService.nextId());
            statement.setString(2, "name" + i);
            statement.setDate(3, new Date(System.currentTimeMillis()));
            statement.setString(4, "remark" + i);
            statement.addBatch();
        }
        long start = System.currentTimeMillis();
        statement.executeBatch();
        connection.commit();
        
        statement.close();
        connection.close();
        System.out.print("耗时:");
        System.out.println(System.currentTimeMillis() - start);
    }
复制代码

 

  测试结果:100万条数据,秒插入

 

 

 

 

 

 

posted @   下课后我要去放牛  阅读(2251)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示