袁来如此的工作笔记
袁来如此的工作笔记
竹杖芒鞋轻胜马,谁怕? 一蓑烟雨任平生。

PHP中快速插入大批量数据的方法

浏览量:543

 一般情况下,我们在进行数据库插入操作时面对较小数量的数据,直接使用insert into语句即可。但是当面对大批量的数据(百万数量级)时,直接使用insert into语句就显得太慢了,需要使用其他的方法。下面记录一种较快的方法,并且和直接使用insert into语句做一个比较:

直接使用insert into语句:

echo "start time:".date("H:i:s");//打印出开始插入数据的时间
for($i = 1;$i<count($matches[1]);$i++){
$this->getsql();
$sql = "INSERT INTO `zixishi`(`tr_id`, `jiaoshi_id`, `jiaoshi_name`,`jiaoshi_category`) VALUES('{$this->create_guid('ligoudan')}', '{$matches[1][$i]}','{$matches[2][$i]}','{$matches[3][$i]}')";
mysql_query($sql);
}
echo "\r\r\r*********end time:".date("H:i:s"),"\r\r\r******all counts:".count($matches[1]);//输出插入数据结束时的时间和插入的数据行数(count()函数)

200条数据大概用时12秒的时间完成所有的插入操作;


使用优化的SQL语句:将sql语句拼接成insert into table1 value (v1, v2, v3), (x1,x2,x3),....然后一次性插入,而不是insert into table1 value (v1, v2, v3);insert into table1 value (x1,x2,x3);这样一条一条的插入;

echo "start time:".date("H:i:s");//打印出开始插入数据的时间
$this->getsql();
$sql = "INSERT INTO `zixishi`(`tr_id`, `jiaoshi_id`, `jiaoshi_name`,`jiaoshi_category`) VALUES ";
for($i=1;$i<count($matches[1]);$i++){
 $sql.="('{$this->create_guid('ligoudan')}', '{$matches[1][$i]}','{$matches[2][$i]}','{$matches[3][$i]}'),";
}
$sql = substr($sql,0,strlen($sql)-1);
mysql_query($sql);//执行批量插入数据操作
echo "\r\r\r*********end time:".date("H:i:s"),"\r\r\r******all counts:".count($matches[1]);//输出插入结束时的时间和插入的数据行数(count()函数)

200条数据用时不超过1秒钟,速度大大提升。



打赏