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>
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>