This article mainly introduces PHP large-volume Insert database 3 methods and speed comparison, 3 ways to use ordinary INSERT statement, INSERT INTO statement and transaction submission, the need for friends can refer to the following
The first method: use INSERT INTO to insert, the code is as follows:$params= Array (' Value'=' -(set_time_limit);0); Echo Date ("H:i:s"); for($i =0; $i <2000000; $i + +) {$connect _mysql->insert ($params);}; echo Date ("H:i:s"), and last shown as: -: -: to A: +: toIt took more than 2 hours!
The second method: Use transaction Commit, BULK Insert database (under 10W per submission) last display
The time consumed is: A: About: - at:Geneva:xx, 8 minutes, 13 seconds.
The code is as follows:echo Date ("H:i:s"); $connect _mysql->query (' BEGIN');$params= Array (' Value'=' -); for($i =0; $i <2000000; $i + +) {$connect _mysql->insert ($params); if($i%100000==0) {$connect _mysql->query (' COMMIT');$connect _mysql->query (' BEGIN'); }} $connect _mysql->query (' COMMIT');echo Date ("H:i:s");
The third approach: using optimized SQL statements: Splicing SQL statements, using INSERT into table () values (), (), (), () and then inserting them once, if the string is too long, you need to configure MySQL to run on the MySQL command line:Set GlobalMax_allowed_packet =2*1024x768*1024x768*Ten;
Consumption time is: One: -: . One: -: .inserting 200W test data took only 1 minutes!The code is as follows:$sql="INSERT into twenty_million (value) values"; for($i =0; $i <2000000; $i + +) {$sql.= "('50′), ";}; $sql= substr ($sql,0, strlen ($sql)-1); $connect _mysql-query ($sql);
Finally, when inserting large quantities of data, the first method is undoubtedly the worst, and the second method is widely used in practical applications, and the third method is more suitable for inserting test data or other low requirements, and it is really fast.
PHP 3 ways to insert databases in large batches and speed comparison