海绵宝宝撒
值得注意的是,我看到许多用户建议迭代INSERT语句,而不是像选择的答案那样构建单个字符串查询。我决定只使用两个字段和一个非常基本的INSERT语句运行一个简单的测试:<?phprequire('conn.php');$fname = 'J';$lname = 'M';$time_start = microtime(true);$stmt = $db->
prepare('INSERT INTO table (FirstName, LastName) VALUES (:fname, :lname)');for($i = 1; $i <= 10; $i++ ) {
$stmt->bindParam(':fname', $fname);
$stmt->bindParam(':lname', $lname);
$stmt->execute();
$fname .= 'O';
$lname .= 'A';}$time_end = microtime(true);$time = $time_end - $time_start;echo "Completed in ". $time ." seconds <hr>";
$fname2 = 'J';$lname2 = 'M';$time_start2 = microtime(true);$qry = 'INSERT INTO table (FirstName, LastName) VALUES ';
$qry .= "(?,?), ";$qry .= "(?,?), ";$qry .= "(?,?), ";$qry .= "(?,?), ";$qry .= "(?,?), ";$qry .= "(?,?), ";$qry .= "(?,?), ";
$qry .= "(?,?), ";$qry .= "(?,?), ";$qry .= "(?,?)";$stmt2 = $db->prepare($qry);$values = array();for($j = 1; $j<=10; $j++) {
$values2 = array($fname2, $lname2);
$values = array_merge($values,$values2);
$fname2 .= 'O';
$lname2 .= 'A';}$stmt2->execute($values);$time_end2 = microtime(true);$time2 = $time_end2 - $time_start2;echo "Completed in ".
$time2 ." seconds <hr>";?>虽然整个查询本身花费了毫秒或更短的时间,但后者(单个字符串)的查询速度始终是原来的8倍或更快。如果这是为了反映更多列上数千行的导入,则差异可能是巨大的。