mysql foreach 批量操作

本文介绍了一个功能实现案例,通过自定义POJO类批量修改报警过滤设置,并使用MyBatis进行数据库操作,包括更新记录和处理重复键的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近需要做个功能,批量修改报警过滤

1.pojo

public class AlarmFilterCustom extends AlarmFilter {
    private String wtitle; // 默认的标题
    private String lang; // 语言
    private String orderby; // 排序字段
    private String likename; // 模糊检索类
    private List<AlarmFilterCustom> filter; // 更新的数组,做mysql批量操作的参数
    private Integer grpid;
    private String text;

省略set,get方法}

   

2.AlarmFilterCustom param = new AlarmFilterCustom();
            for(int i = 0; i < alarmFilterCustoms.size(); i++){
                alarmFilterCustoms.get(i).setUid(userInfo.getGid());
            }
            param.setFilter(alarmFilterCustoms);

3.    <!-- 新增数据 -->
    <insert id="addAlarmRecord" parameterType="java.util.List" useGeneratedKeys="true"
        keyProperty="id">
        
        <foreach collection="filter" index="index" item="item" separator=";">
        insert into t_alarmfilter (uid, aid, notice, web, app, mail) values 
        ( #{item.uid}, #{item.aid}, #{item.notice}, #{item.web}, #{item.app}, #{item.mail})
        ON DUPLICATE KEY UPDATE //判断是执行新增还是更新,如果数据库存在uid,aid相同的数据,则更新,否则新增
         uid = #{item.uid}, aid = #{item.aid}, notice = #{item.notice}
        </foreach> 
        
        
    </insert>

4.mysql,表配置


二:
1.jsp
  var data = {batch: []}
    for (var i = 0; i < idlist.length; i++) {
        data.batch.push(idlist[i]);
    }
   
    
    data = JSON.stringify(data);
    data = encodeURIComponent(data);
    var _url = '${ctx}/datamotor/alarm/read?data=' + data;

2.后台
        一。ListIntegerParam list = (ListIntegerParam) Common.jsonToObj(data, ListIntegerParam.class);
  AlarmNoticeCustom param = new AlarmNoticeCustom();
            param.setBatch(list.getBatch());
            alarmNoticeService.updateRecord(param);

二。public class ListIntegerParam {
    
    private List<Integer> batch;


    public List<Integer> getBatch() {
        return batch;
    }


    public void setBatch(List<Integer> batch) {
        this.batch = batch;
    }


}
三。pojo

3.xml
    <!-- 批量更新,这里要注意item的长度 mysql对长度有要求,系统中默认配置为2096个字节 -->
    <update id="updateRecord" parameterType="com.s3.po.AlarmNoticeCustom">
        update gps.t_alarmnotice set readed = 1 where id in 
        <foreach collection="batch" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </update>

### 使用 MySQL 进行 foreach 批量插入 为了提高性能并减少网络往返次数,在处理大量数据时推荐使用批量插入而不是逐条插入语句。可以采用以下几种方法来实现高效的 `foreach` 批量插入操作。 #### 方法一:构建单个 INSERT 语句 通过拼接多个值列表到同一个 `INSERT INTO ... VALUES (...)` 语句中,能够显著提升效率[^1]: ```sql INSERT INTO table_name (column1, column2) VALUES (value_set_1), (value_set_2), ...; ``` 例如要插入三组记录,则完整的SQL如下所示: ```sql INSERT INTO users (name, age) VALUES ('Alice', 30), ('Bob', 25), ('Charlie', 35); ``` 这种方法适合于已知所有待插入的数据集较小的情况。 #### 方法二:利用编程语言中的批处理功能 对于较大的数据集合,建议先收集所有的待插入项至内存数组或列表结构内,再一次性发送给数据库执行。以下是 Python 中使用 pymysql 库的一个简单例子: ```python import pymysql connection = pymysql.connect( host='localhost', user='root', password='', database='test_db' ) try: with connection.cursor() as cursor: sql = "INSERT INTO users (name, age) VALUES (%s, %s)" data_to_insert = [ ("David", 40), ("Eve", 28), ("Frank", 37) ] result = cursor.executemany(sql, data_to_insert) finally: connection.commit() connection.close() ``` 此方式不仅简化了代码逻辑而且提高了程序运行速度。 #### 方法三:LOAD DATA INFILE 命令 如果源文件已经存在于服务器上或者可以通过本地路径访问的话,那么可以直接使用 `LOAD DATA INFILE` 来加载CSV或其他分隔符格式的纯文本文件: ```sql LOAD DATA LOCAL INFILE '/path/to/file.csv' INTO TABLE my_table FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'; ``` 这种方式非常适合用来导入大规模静态数据集。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值