最近用到了一些数据库的批量新增修改的功能,整理了一些给自己、也给需要用到的小伙伴
mysql批量新增
mysql实现批量新增原理:根据查询出来的数据批量新增到另一个表;代码如下:
INSERT INTO USER(UserName,PASSWORD,MobileNumber,Mailbox)SELECT 'hello','123',MobileNumber,Mailbox FROM USERTwo
注意:查询的字段和新增的字段必须保持一致,可以自定义字段。
Mybatis
List批量新增、修改
在Mybatis中操作一般使用批量新增的方式如下:
<insert id="insertUser" parameterType="java.util.List" >
<foreach collection="list" item="s" index="index" open="" separator=";" close="">
INSERT INTO user(username, paddword, mobilenumber, mailbox)
VALUES (
#{s.username,jdbcType=VARCHAR},
#{s.paddword,jdbcType=VARCHAR},
#{s.mobilenumber,jdbcType=VARCHAR},
#{s.mailbox,jdbcType=VARCHAR})
</foreach>
</insert>
在Mybatis中操作一般使用批量修改的方式如下:
<update id="updateuser">
<foreach collection="list" item="s" index="index" open="" separator=";" close="">
UPDATE b_dailytask
<set>
<if test="s.username != null">
username = #{s.username,jdbcType=VARCHAR},
</if>
paddword = #{s.paddword,jdbcType=VARCHAR},
mobilenumber = #{s.mobilenumber,jdbcType=VARCHAR},
mailbox = #{s.mailbox,jdbcType=VARCHAR}ype=VARCHAR}
</set>
where userid= #{s.userid,jdbcType=INTEGER}
</foreach>
</update>
Map批量新增
<!--批量新增-->
<insert id="insertBatch" parameterType="java.util.Map">
insert into video_ed (video_id,user_id)
values
<foreach collection="map" item="value" index="key" separator=",">
(#{key}, #{value})
</foreach>
</insert>