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万条数据,秒插入
。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本