码迷,mamicode.com
首页 > 数据库 > 详细

MySQL批量插入、批量更新及批量删除语句

时间:2020-06-18 19:33:43      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:等于   ram   reg   语句   序号   color   reac   map   word   

1、批量插入

  1. <insert
  2. id="insertBatch"
  3. parameterType="java.util.List">
  4. insert into
  5. t_student(name, age, class)
  6. values
  7. <foreach collection="list" item="item" index="index" separator=",">
  8. (
  9. #{item.name,jdbcType=VARCHAR},
  10. #{item.age,jdbcType=INTEGER},
  11. #{item.class,jdbcType=LONGVARCHAR}
  12. )
  13. </foreach>
  14. </insert>

2、批量更新

方式一:

  1. <update id="updateBatch">
  2. <foreach collection="list" separator=";" item="stud">
  3. update t_studetn set
  4. name = #{stud.name},
  5. age = #{stud.age},
  6. class = #{stud.sex},
  7. where id = #{stud.id}
  8. </foreach>
  9. </update>

方式二:

  1. <update id="updateBatch" parameterType="list">
  2. UPDATE t_student
  3. SET name = CASE id
  4. <foreach collection="list" item="i" index="index">
  5. WHEN #{i.id}
  6. THEN #{i.name}
  7. </foreach>
  8. END,
  9. age = CASE id
  10. <foreach collection="list" item="i" index="index">
  11. WHEN #{i.id} THEN #{i.age}
  12. </foreach>
  13. END
  14. WHERE id IN
  15. <foreach collection="list" separator="or" item="i" index="index" >
  16. id=#{i.id}
  17. </foreach>
  18. </update>

3、批量删除

  1. <delete id="deleteBatchByParams">
  2. delete from
  3. t_student
  4. where
  5. id IN
  6. <foreach collection="ids" item="item" index="index" open="("close=")"separator=",">
  7. #{item}
  8. </foreach>
  9. </delete>

 

 

item 循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。
具体说明:在list和数组中是其中的对象,在map中是value。
该参数为必选。
collection

要做foreach的对象,作为入参时,List<?>对象默认用list代替作为键,数组对象有array代替作为键,Map对象没有默认的键。
当然在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:
如果User有属性List ids。入参是User对象,那么这个collection = "ids"
如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"
上面只是举例,具体collection等于什么,就看你想对那个元素做循环。
该参数为必选。

separator 元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
open foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选。
close foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。
index 在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。
 

https://blog.csdn.net/u014252478/article/details/91386289

MySQL批量插入、批量更新及批量删除语句

标签:等于   ram   reg   语句   序号   color   reac   map   word   

原文地址:https://www.cnblogs.com/niudaxianren/p/13158978.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!