set_time_limit(800);$dsn = 'mysql:host=localhost;dbname=test';$db = new PDO($dsn,'root','',array(PDO::ATTR_PERSISTENT => true)); //刪除上次的插入數據$db->query ...
set_time_limit(800);
$dsn = 'mysql:host=localhost;dbname=test';
$db = new PDO($dsn,'root','',array(PDO::ATTR_PERSISTENT => true));
//刪除上次的插入數據
$db->query('delete from `test`');
//開始計時
$start_time = time();
$sum = 5000000;
// 測試選項
$num = 2;
/*
$values = '';
for ($i = 1; $i < $sum; $i++) {
$values .= "($i, 'testtest'),";
}
$values = trim($values, ',');
$db->query("insert into `test` (`id`, `name`) values $values");
*/
if ($num == 1){
// 單條插入
for($i = 0; $i < $sum; $i++){
$db->query("insert into `test` (`id`,`name`) values ($i,'tsetssdf')");
}
} elseif ($num == 2) {
// 批量插入,為了不超過max_allowed_packet,選擇每10萬插入一次
for ($i = 0; $i < $sum; $i++) {
if ($i == $sum - 1) { //最後一次
$time = time();
if ($i%10000 == 0){
$values = "('testtest', $time)";
$db->query("insert into `test` ( `name`, `ctime`) values $values");
} else {
$values .= ",('testtest', $time)";
$db->query("insert into `test` (`name`, `ctime`) values $values");
}
break;
}
if ($i%10000 == 0) { //平常只有在這個情況下才插入
if ($i == 0){
$time = time();
$values = "('testtest', $time)";
} else {
$values = trim($values, ',');
$db->query("insert into `test` (`name`, `ctime`) values $values");
$values = "($i, 'testtest')";
}
} else {
$time = time();
$values .= ",('testtest', $time)";
}
}
} elseif ($num == 3) {
// 事務插入
$db->beginTransaction();
for($i = 0; $i < $sum; $i++){
$db->query("insert into `test` (`id`,`name`) values ($i,'tsetssdf')");
}
$db->commit();
} elseif ($num == 4) {
// 文件load data
$filename = dirname(__FILE__).'/test.sql';
$fp = fopen($filename, 'w');
for($i = 0; $i < $sum; $i++){
fputs($fp, "$i,'testtest'\r\n");
}
$db->exec("load data infile '$filename' into table test fields terminated by ','");
}
$end_time = time();
echo "總耗時", ($end_time - $start_time), "秒\n";
echo "峰值記憶體", round(memory_get_peak_usage()/1000), "KB\n";
/*
* 1 批量個數儘量控制在10000以下
* 2 查詢時 MyIASM 明顯比 Innodb快
*/
參考
http://www.codeceo.com/article/mysql-insert-compare.html