日期:2014-05-16  浏览次数:20961 次

mysql中insert into和replace into 使用小记

[mysql]

insert into 和 replace into 两者的区别是

insert into 是向一张表中插入记录

replace into 则是有插入和覆盖的功能,插入和insert into 是一样的,覆盖则是以主键,其次是唯一键为准的,即:

数据表中有以下数据:

主键ID 名称 备注
1 admin 这是管理员
2 user1 这是操作员

执行了 replace into 表名 values (1,'root','这是管理员');后

数据即修改为:

主键ID 名称 备注
1 root 这是管理员
2 user1 这是操作员

以上简单的说明replace into的作用

?

mysql 中insert into 批量添加的作用

场景:

有一存放学生对象的List集合,size为10000,需要持久化到数据库中

做法一:

遍历该List集合,将对象一个一个取出来执行insert into语句,相信这种做法是一般程序员采用的,很简单。

做法二:

利用mysql的insert into 表名 values (.....),(.....),(.....),(.....) 特性一次性大批量的插入数据,提高效率

[java]

备注:我用的是ibatis

业务层:

private void batchInsertAct(List<ProgramDetail> acts) throws DataBaseException {
        Map<Integer, List<ProgramDetail>> map = this.groupListBySize(acts, GROUP_SIZE);
        if ((map != null) && !map.isEmpty()) {
            for (Integer key : map.keySet()) {
                Map<String, Object> paramaters = new HashMap<String, Object>();
                paramaters.put("acts", map.get(key));
                this.programDetailDao.batchInsertAct(paramaters);
            }
        }
    }

?数据库层:

<insert id="batchInsertAct" parameterClass="map">
	   <![CDATA[
	   		INSERT INTO T_PROGRAMDETAIL(PROGRAMDETAILID,PROGRAMLISTID,PROGRAMTIME,PROGRAMNAME,VISIBLE,COLLATESTATE,VIDEOSTARTTIME,VIDEOENDTIME) VALUES
	   ]]>
	   <iterate property="acts" conjunction=",">
	        <![CDATA[
	           (null,#acts[].programListId#, #acts[].programTime#, #acts[].programName#, 0, #acts[].collateState#, #acts[].videoStartTime#, #acts[].videoEndTime#) 
	        ]]>
	   </iterate>
   </insert>

?

? 利用mysql的replace into 表名 values (.....),(.....),(.....),(.....) 特性一次性大批量的修改数据,提高效率

业务层:

private void batchUpdateAct(List<ProgramDetail> acts) throws DataBaseException {
        Map<Integer, List<ProgramDetail>> map = this.groupListBySize(acts, GROUP_SIZE);
        if ((map != null) && !map.isEmpty()) {
            for (Integer key : map.keySet()) {
                Map<String, Object> paramaters = new HashMap<String, Object>();
                paramaters.put("acts", map.get(key));
                this.programDetailDao.batchUpdateAct(paramaters);
            }
        }
    }

?数据库层:

<insert id="batchUpdateAct" parameterClass="map">
	   <![CDATA[
	   		REPLACE INTO T_PROGRAMDETAIL(PROGRAMDETAILID,PROGRAMLISTID,PROGRAMTIME,PROGRAMNAME,VISIBLE,COLLATESTATE,VIDEOSTARTTIME,VIDEOENDTIME) VALUES
	   ]]>
	   <iterate property="acts" conjunction=",">
	        <![CDATA[
	           (#acts[].programDetailId#,#acts[].programListId#, #acts[].programTime#, #acts[].programName#, 0, #acts[].collateState#, #acts[].videoStartTime#, #acts[].videoEndTime#) 
	        ]]>
	   </iterate>
   </insert>

?

呵呵 随笔而已,格式有点乱,有什么问题或疑问,各位大神请联系我!?

?

?