-3

我有一个包含 65000 条记录的 csv 文件,我需要将其导入到我的数据库中。

我尝试过以下代码,但速度很慢。

无论如何我可以更快地做到这一点。

@set_time_limit(1200);
    $file = './csvFiles/aw_Products.csv';
    $handle = fopen( $file , 'r');
    while (($row = fgetcsv($handle)) !== false) {       
        if( is_integer($row[0]) || $row[0] != 0 )
        {
            $product = new Product();
            $product->merchant_id       = $row[0];
            $product->merc_product_id   = $row[1];
            $product->product_id        = $row[2];
            $product->product_name      = $row[3];
            $product->product_desc      = htmlentities($row[4]);
            //$product->keywords            = htmlentities($row[6]);
            $product->category_id       = $row[5];
            $product->link_url          = $row[6];
            $product->image_url         = $row[7];
            $product->price             = $row[8];
            $product->delivery_cost     = $row[9];
            //$product->deliveryAvailable   = $row[12];
            //$product->deliveryDetails = $row[13];
            //$product->valid_to            = $row[14];
            //$product->valid_from      = ($row[3] == 'yes') ? 1 : 0;

            if( Product::find_by_id( $row[0] ) )
                $product->updateRecord();
            else
                $product->createRecord();
        }
        sleep (1);
    }
    fclose($handle);
4

2 回答 2

2

sleep() is probably the culprit. But I am also wondering about this: Product::find_by_id() because it might be doing a SELECT query for every INSERT. You might think about making a single SELECT query to get all of the existing DB keys into a PHP array, then you can use *in_array()* to check whether to UPDATE or INSERT. Probably goes without saying, but you will want to add to the PHP array if you INSERT.

于 2012-12-16T16:47:11.107 回答
1

放弃 sleep() 并使用准备好的语句进行 mysql 插入/更新。

于 2012-12-16T17:26:36.660 回答