Yii inserts multiple data records

Source: Internet
Author: User

How to Use yii to insert multiple data records at a time is very difficult. Today, I tried to look at the source code and thought of a way. If there is any error, please contact me in time to correct it in order to avoid misleading others, I hope you can refer to this blog for more information.


Look at the code with little nonsense:

$ Db = Yii: app ()-> db; $ transaction = $ db-> beginTransaction (); $ command = $ db-> createCommand (); try {$ _ files = array ('name' => 'abc', 'SIZE' => '000000'), array ('name' => 'abc2 ', 'SIZE' => '000000'), array ('name' => 'abc3', 'SIZE' => '000000'); if ($ _ files) {foreach ($ _ files as $ files) {$ command-> reset (); foreach ($ files as $ k => $ v) {$ columArray [$ k] = $ v;} $ command-> insert (FileConvert: model ()-> tableName (), $ columArray );}} $ transaction-> commit (); return true;} catch (Exception $ e) {$ transaction-> rollback (); // if the operation fails, return false for data rollback ;}


After the command is reset with reset () for each loop, insert does not drop excetue () for execution, because it will be automatically executed during commit, so that you can insert multiple pieces of data at a time without having to spell SQL.

However, this is a drawback. If you execute a lot of items at a time, the efficiency will be slow. After all, this is equivalent to executing multiple such SQL statements: insert into table values ('A', 'B ');

The SQL statement we manually spell is as follows: insert into table values ('A', 'B'), ('C', 'D'); this is relatively more efficient.

Therefore, if less data is written, you can use the above method.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.