我想知道预准备语句是否与具有多个值的普通mysql_query一样工作。
INSERT INTO table (a,b) VALUES ('a','b'), ('c','d');VS
$sql = $db->prepare('INSERT INTO table (a,b) VALUES (?, ?);如果我在循环中使用准备好的语句,MySQL是否会在后台优化插入以使其像在第一段代码中那样工作,或者只是像每次使用一个值运行循环中的第一段代码一样?
发布于 2009-09-28 17:05:10
我继续运行了一个测试,其中一个查询使用预准备语句,另一个查询构建整个查询,然后执行该查询。我可能没有让我想知道的东西变得容易理解。
这是我的测试代码。我认为准备好的语句会延迟执行,直到$stmt->close()被调用来优化它或其他什么。但情况似乎并非如此,因为使用real_escape_string构建查询的测试速度至少快了10倍。
<?php
$db = new mysqli('localhost', 'user', 'pass', 'test');
$start = microtime(true);
$a = 'a';
$b = 'b';
$sql = $db->prepare('INSERT INTO multi (a,b) VALUES(?, ?)');
$sql->bind_param('ss', $a, $b);
for($i = 0; $i < 10000; $i++)
{
$a = chr($i % 1);
$b = chr($i % 2);
$sql->execute();
}
$sql->close();
echo microtime(true) - $start;
$db->close();
?>发布于 2009-09-28 16:39:41
如果在循环中使用预准备语句,这将比每次运行原始查询效率更高,因为只需要对预准备语句执行一次分析。所以不,在那个程度上,它是不一样的。
发布于 2014-07-21 21:28:46
public function insertMulti($table, $columns = array(), $records = array(), $safe = false) {
self::$counter++;
//Make sure the arrays aren't empty
if (empty($columns) || empty($records)) {
return false;
}
// If set safe to true: set records values to html real escape safe html
if($safe === true){
$records = $this->filter($records);
}
//Count the number of fields to ensure insertion statements do not exceed the same num
$number_columns = count($columns);
//Start a counter for the rows
$added = 0;
//Start the query
$sql = "INSERT INTO " . $table;
$fields = array();
//Loop through the columns for insertion preparation
foreach ($columns as $field) {
$fields[] = '`' . $field . '`';
}
$fields = ' (' . implode(', ', $fields) . ')';
//Loop through the records to insert
$values = array();
foreach ($records as $record) {
//Only add a record if the values match the number of columns
if (count($record) == $number_columns) {
$values[] = '(\'' . implode('\', \'', array_values($record)) . '\')';
$added++;
}
}
$values = implode(', ', $values);
$sql .= $fields . ' VALUES ' . $values;
//echo $sql;
$query = $this->dbConnection->query($sql);
if ($this->dbConnection->error) {
$this->errorLog($this->dbConnection->error, $sql);
return false;
} else {
return $added;
}
}此函数用于首先准备具有多个行值的一次插入查询,然后插入它一次。但这并不是立即进行大容量插入。
https://stackoverflow.com/questions/1488033
复制相似问题