mysql批量插入以及批量更新

1、mysql批量插入

1.SQL語句html

INSERT INTO table_name (col_name1, col_name2,...) VALUES(col_value1,col_value2,...), (col_value1,col_value2,...)

2.注意事項java

mysql語句並非越長越好,mysql語句長度有限制,能夠查看mysql的配置文件my.in中max_allowed_packet屬性,並進行相應設置(好比max_allowed_packet = 20M)。

3.案例(使用java和mybatis)mysql

java代碼:sql

int saveAll(Collection<AccountBank> accountBankList);

mybatis的xml代碼:mybatis

<insert id="saveAll" parameterType="collection">
        INSERT INTO account_bank (user_id, bank_no, bank, branch, province, city, area, add_time, add_ip, status,
        pic_path, tpp_card_id, mobile_phone)
        VALUES
        <foreach collection="list" item="item" index="index"
                 separator=",">
            (#{item.userId}, #{item.bankNo}, #{item.bank}, #{item.branch}, #{item.province}, #{item.city}, #{item.area}, #{item.addTime}, #{item.addIp}, #{item.status}, #{item.picPath}, #{item.tppCardId}, #{item.mobilePhone})
        </foreach>
 </insert>

2、mysql批量更新

1.SQL語句code

INSERT INTO table_name (col_name1, col_name2,...)  VALUES(col_value1,col_value2,...), (col_value1,col_value2,...) ON DUPLICATE KEY UPDATE col_name1=VALUES(col_name1), col_name2= VALUES(col_name2)

2.注意事項xml

它的實現原理是,首先mysql根據表名後面列出的主鍵,查找表(由於是主鍵,因此在表中惟一存在)。若是存在該行數據,則按照最後的col_name = values(col_name)列表對相應的字段,按照values列表中給出的值進行更新。

3.案例(使用java和mybatis)htm

java代碼:ip

int updateAll(Collection<User> userList);

mybatis的xml代碼:ci

<insert id="updateAll" parameterType="collection">
        INSERT INTO user(user_id, email, card_id, real_name, tpp_user_cust_id, tpp_user_id, tpp_account_id
        )
        VALUES
        <foreach collection="list" item="item" index="index"
                 separator=",">
            (#{item.userId}, #{item.email}, #{item.cardId}, #{item.realName}, #{item.tppUserCustId}, #{item.tppUserId},
            #{item.tppAccountId}
            )
        </foreach>
        ON DUPLICATE KEY UPDATE email=VALUES(email),card_id=VALUES(card_id),real_name=VALUES(real_name),
        tpp_user_cust_id=VALUES(tpp_user_cust_id),tpp_user_id=VALUES(tpp_user_id), tpp_account_id=VALUES(tpp_account_id)
 </insert>

3、參考的文章

  1. 《MySql快速插入以及批量更新》http://www.2cto.com/database/201304/202410.html
相關文章
相關標籤/搜索