現在有這樣一個表,我們要往這個表裡面插入大量資料該如何實作呢?
CREATE TABLE IF NOT EXISTS `user_info` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增主键', `name` varchar(255) NOT NULL default '' COMMENT '姓名', `age` int(11) NOT NULL default '0' COMMENT '年龄', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户信息表';
批次插入
方法一、使用for循環插入
在往mysql插入少量資料的時候,我們一般用for迴圈
(相關影片教學分享:php影片教學)
$arr = [ [ 'name' => 'testname1', 'age' => 18, ], [ 'name' => 'testname2', 'age' => 19, ], [ 'name' => 'testname3', 'age' => 18, ], ]; $servername = "localhost"; $port = 3306; $username = "username"; $password = "password"; $dbname = "mytestdb"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname, $port); // 检测连接 if ($conn->connect_error) { die("connect failed: " . $conn->connect_error); } $costBegin = microtime(true); foreach($arr as $item) { $sql = sprintf("INSERT INTO user_info (name, age) VALUES ( '%s', %d);", $item['name'], (int)$item['age']); if ($conn->query($sql) === TRUE) { echo "insert success"; } else { echo "Error: " . $sql . "
" . $conn->error; } } $costEnd = microtime(true); $cost = round($costEnd - $costBegin, 3); var_dump($cost); $conn->close();
假如說要批次插入大量數據,如果還用for迴圈的辦法插入是沒有問題的,只是時間會比較長。比較一下插入少量資料與插入大量數據,使用上面的for迴圈插入耗費的時間:條數時間(單位:秒)
INSERT INTO user_info (name, age) VALUES ('name1', 18), ('name2', 19);表示一次插入两条数据 $arr = [ [ 'name' => 'testname1', 'age' => 18, ], [ 'name' => 'testname2', 'age' => 19, ], [ 'name' => 'testname3', 'age' => 18, ], // 此处省略 …… …… ]; $servername = "localhost"; $port = 3306; $username = "username"; $password = "password"; $dbname = "mytestdb"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname, $port); // 检测连接 if ($conn->connect_error) { die("connect failed: " . $conn->connect_error); } $costBegin = microtime(true); if (!empty($arr)) { $sql = sprintf("INSERT INTO user_info (name, age) VALUES "); foreach($arr as $item) { $itemStr = '( '; $itemStr .= sprintf("'%s', %d", $item['name'], (int)$item['age']); $itemStr .= '),'; $sql .= $itemStr; } // 去除最后一个逗号,并且加上结束分号 $sql = rtrim($sql, ','); $sql .= ';'; if ($conn->query($sql) === TRUE) { } else { echo "Error: " . $sql . "
" . $conn->error; } } $costEnd = microtime(true); $cost = round($costEnd - $costBegin, 3); var_dump($cost); $conn->close();
以上是php實作向mysql批量插入數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!