【发布时间】:2011-08-02 17:05:07
【问题描述】:
我得到了一个 650 行的数组。在我的本地计算机上使用 PDO 插入它需要 10-15 秒。 那很慢。这是因为磁盘读/写吗?或者是别的什么?
这是我的数组(前 4 行):
Array
(
[0] => Array
(
[0] => 3
[1] => 1
)
[1] => Array
(
[0] => 3
[1] => 2
)
[2] => Array
(
[0] => 3
[1] => 5
)
[3] => Array
(
[0] => 8
[1] => 1
)
)
这是我的代码:
$stmt = $this->db->prepare("INSERT INTO sl_link_store_category (item_a_ID, item_b_ID) VALUES (:item_a_ID, :item_b_ID)");
foreach($my_array as $row) {
$stmt->execute(array(':item_a_ID' => $row[0], ':item_b_ID' => $row[1]));
}
解决方案
对于那些想知道的人,她是我插入多行的解决方案
只使用一个$stmt->execute:
$input_arr; // This array one has lots of values
$sql = "INSERT INTO sl_link_store_category (field_a, field_b) VALUES ";
$i = 0;
// I create the query string with unique prepared values
// I could probably have used a for loop since I'm not using any
// values from $row
foreach($input_arr as $row) {
$i++;
$sql .= "(:field_a_$i, :field_a_$i), ";
}
// Remove the last comma (and white space at the end)
$sql = substr(trim($sql), 0, -1);
$stmt = $this->db->prepare($sql);
// I need to create a new associative array with field name
// matching the prepared values in the SQL statement.
$i = 0;
$arr = array();
foreach($input_arr as $row) {
$i++;
$arr[":field_a_$i"] = $row[0];
$arr[":field_b_$i"] = $row[1];
}
$stmt->execute($arr);
}
【问题讨论】:
-
您使用的是什么数据库引擎(MyISAM、InnoDB...)?
-
@konforce - 我正在使用 InnobDB。
-
那么您可能需要考虑在您的开发机器上的 MySQL 配置中设置
innodb_flush_log_at_trx_commit=2和sync_binlog=0。这将最大限度地减少磁盘刷新,并可以通过多种因素加速您的应用程序。