The first method: use INSERT INTO to insert, the code is as follows:
?
1234567 |
$params = array (‘value ‘=>‘ 50′); set_time_limit(0); echo date (“H:i:s”); for ( $i =0; $i <2000000; $i ++){ $connect_mysql ->insert( $params ); }; echo date (“H:i:s”); |
The last display is: 23:25:05-01:32:05 that took more than 2 hours!
The second method: use transaction commit, BULK Insert database (under 10W per submission) Last display time consumed is: 22:56:13 23:04:00, altogether 8 minutes 13 seconds, the code is as follows:
?
1 2 3 4 5 6 7 8 9 Ten One A |
echo date (“H:i:s”); $connect_mysql ->query(‘BEGIN‘); $params = array (‘value ‘=>‘ 50′); 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 global max_allowed_packet = 2*1024*1024*10; consumption time: 11:24:06 11:25:06;
Inserting 200W test data only took 1 minutes! The code is as follows:
?
1 2 3 4 5 6 |
$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