开发者社区 问答 正文

多条数据的List如何简便的批量提交到MySQL呢?

已有包含16500条数据的List,无法一次性提交到MySQL,因为已超过MySQL的max_allowed_packet故考虑每1000条提交一次,最先想到的是16500 / 1000 = 16,然后定义int start、int end根据start、end不断获取该List的subList,然后再逐个提交subList。但是总觉得这种方式不够好,前辈们如果遇到这种情况会想要怎么解决呢?

展开
收起
蛮大人123 2016-03-06 15:25:31 2609 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    这是基于ibatis batch insert的代码,从项目中抠出来的,希望能对你有所帮助

     protected <E> boolean executeBatch(List<E> elist, String sqlId) throws SQLException {
            boolean isAutoCommit = true;
            SqlMapClient sqlMapClient = this.getSqlMapClient();
            try {
                sqlMapClient.startTransaction();
                sqlMapClient.startBatch();
                isAutoCommit = sqlMapClient.getCurrentConnection().getAutoCommit();
                sqlMapClient.getCurrentConnection().setAutoCommit(false);
     
                int flag = 0;
                for (int i = 0, size = elist.size(); i < size; ++i) {
                    sqlMapClient.insert(sqlId, elist.get(i));
                    if (++flag == 200) {
                        flag = 0;
                        sqlMapClient.executeBatch();
                    }
                }
                sqlMapClient.executeBatch();
                sqlMapClient.commitTransaction();
            } catch (SQLException e) {
                sqlMapClient.getCurrentConnection().rollback();// 事务回滚
                throw new SQLException(e.getCause());
            } finally {
                sqlMapClient.getCurrentConnection().setAutoCommit(isAutoCommit);// 恢复原来的状态
                sqlMapClient.endTransaction();
            }
            return true;
        }
    2019-07-17 18:54:43
    赞同 展开评论