1. 程式人生 > 實用技巧 >資料大批量遷移處理

資料大批量遷移處理

在大批量遷移資料的時候,有多種可行的方式;

1、一次查詢,然後insetAll插入。但這種方式也有數量上限。

2、分批查詢再插入,但是這種量大後會很慢很慢

還有一種推薦的,利用mysqlimport命令,和前兩個相比,速度極快

$str = '';
foreach ($addData as $v) {
    $str .= $v['name'] . "\t" . $v['image'] . "\t" . $v['difficultyLevel'] . "\t" . $v['categoryId'] . "\t" . $v['source'] . "\t" . $v['introduce'] . "\t" . $v
['isHasVideo'] . "\t" . $v['description'] . "\t" . $v['cookTime'] . "\t" . $v['unit'] . "\t" . $v['calories'] . "\t" . $v['thirdId'] . "\t" . $v['thirdNo'] . "\t" . $v['createTime'] . "\t" . $v['updateTime'] . "\t" . $v['status'] . "\t" . $v['nutrition'] . "\n"; } //寫入到檔案 $re = file_put_contents("/tmp/detail.txt", $str
); //執行匯入資料命令 //注意密碼用單引號,注意賬號許可權,注意格式 $cmd = '/usr/local/mysql/bin/mysqlimport -h' . config("database.db_test.hostname") . ' -u' . config("database.db_test.username") . ' -p\'' . config("database.db_test.password") . '\' db_test /tmp/detail.txt --columns=\'name,image,difficultyLevel,categoryId,source,introduce,isHasVideo,description,cookTime,unit,calories,thirdId,thirdNo,createTime,updateTime,status,nutrition\' -L';
shell_exec($cmd);

10萬條的資料 ,基本10秒內插入成功。還是賊拉快的。

注意 快取檔案讀寫許可權要有。欄位要對應。表名和快取檔名要一致(detail)。資料庫密碼加引號(部分密碼裡有特殊符號) 伺服器要開啟shell_exec許可權。