簡體   English   中英

如何將CSV文件導入MySQL更快速的codeigniter

[英]How to import csv file to mysql more faster codeigniter

它可以正常工作,但是當我在CSV文件中導入近2500行以上的大文件時,它會緩慢加載/導入,並說出錯誤,但是有些文件正在插入,有些則沒有。 我的問題是有什么方法可以使其更快地導入? 我在文件中看到但我不知道如何使用它。

碼:

    function convert_csv($id){
                if (empty($id)) redirect("contracts");
                $config['upload_path']   = './files/contracts-csv/'; 
                $config['allowed_types'] = 'csv';   
                $config['max_size']      = '4096';      
                $config['overwrite']     =  TRUE;

                $this->load->library('upload', $config);
                $this->upload->display_errors('', '');

                if (!$this->upload->do_upload("csv_file")) {
                      echo $this->upload->display_errors(); die();
                      $this->data['error'] = array('error' => $this->upload->display_errors());
                } else {
                    $upload_result = $this->upload->data();
                    $upload_result = $this->upload->data(); 
                    $this->load->library('csvreader');
                    $result =   $this->csvreader->parse_file("./files/contracts-csv/".$upload_result['file_name']);
                    $date_today = date('Y-m-d H:i:s');
                        foreach ($result as $v) {
                            $this->contract_items->add_serial($v,$id,$date_today);
                        }
                }
}

在CodeIgniter中使用MySQL事務 ,它將大大加快一切速度(例如,制作500個項目的塊並將它們插入一個事務中)。

但是,如果它以錯誤結尾,則問題可能出在其他地方。 2500不是很多。

csv中行的每次迭代都會執行以下操作:

  • 建立插入SQL
  • 發送到數據庫布局
  • 得到回應

您可以嘗試構建如下的批量sql:

insert into table_name (f1, f2, f3) values ("val1", "val2", "val3"), ("val2_1", "val2_2", "val2_3"),...

大約100-200 '("val1", "val2", "val3")'塊應該更快,但是我不知道代碼初始化緩存和其他東西如何...

您可以將其包裝在insert_batch查詢中。

$your_data = array();
foreach ($result as $v) {
    $your_data[] = array(
        'v' => $v,
        'id' => $id,
        'date_today' => $today,
    );
);

$this->db->insert_batch('your_table_name', $your_data);

這將整個事情作為單個查詢運行。 這應該比多個查詢更快。 確切的代碼由您決定,因為我不知道$this->contract_items->add_serial這樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM