Mysql
 sql >> Database >  >> RDS >> Mysql

come ottimizzare questo codice php di inserimento sql?

Grazie mille tadman e Hanlet Escaño e Uueerdo e Julie Pelletier e Solarflare per avermi aiutato nei commenti.

Ho apportato 3 diverse modifiche al mio codice PHP utilizzando gli approcci che hai suggerito nei commenti, quindi ho testato i risultati ed ecco i risultati dei test.

La conclusione dei 3 test: come suggerito da tadman, la chiave è in LOAD DATA INFILE . ha ridotto drasticamente il tempo di esecuzione a meno di 7 secondi, e questi sono i 3 test.

CODICE ORIGINALE: ~ 26 minuti

PROVA 1 : ~ 34 minuti

(come Uueerdo mi ha suggerito di rimuovere echo istruzioni e il contatore di righe del ciclo)

while(!feof($filehandle)){
// $x++; // commented out
//echo $x . ":  "; // commented out
$fileline = fgets($filehandle);
$fields = explode("\t", $fileline);
$query = "INSERT INTO products(hs,arabicname,englishname) VALUES(" . "'" . str_replace("'", ".", $fields[0]) ."'," . "'". str_replace("'", ".", $fields[1]) . "'," . "'". str_replace("'", ".", $fields[2]) . "');"; 
$result = $conn->query($query); 
/* // commented out
if(!$result) {echo  $conn->error . "</br>";}
}else{echo $result . "</br>";}
*/};

PROVA 2 : ~ 7 secondi

(Come tadman detto che ho cercato LOAD DATA INFILE ed era super potente

//replace the entire loop with this simple query
$query = "LOAD DATA LOCAL INFILE'" . 
addslashes("C:\\xampp\\htdocs\\bots\\impandexp\\imports.txt")
. "' INTO TABLE imports FIELDS TERMINATED BY '\t' LINES TERMINATED BY
'\r\n'(product_hs,counteryname,units,weight,value) SET  year = '2014';";
 $result = $conn->query($query);

PROVA 3 : ~ 5 secondi

Era lo stesso del test 2, tranne per il fatto che ho trovato utili suggerimenti nella stessa pagina fornita da tadman, che aiutano a massimizzare la velocità per.

Caricamento in blocco di dati per tabelle InnoDB

// turning off index checks that might slows down bulk data insertion
$query = "SET foreign_key_checks=0;";
$conn->query($query);
$query = "SET unique_checks=0;";
$conn->query($query);
$query ="SET autocommit=0;";
$conn->query($query);

$query = "LOAD DATA LOCAL INFILE'" . addslashes("C:\\xampp\\htdocs\\bots\\impandexp\\imports.txt") . "' INTO TABLE imports FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\r\n'(product_hs,counteryname,units,weight,value) SET  year = '2014';";
$result = $conn->query($query);
echo $result . "</br>";
// turning them on again
$query = "SET foreign_key_checks=1;";
$conn->query($query);
$query = "SET unique_checks=1;";
$conn->query($query);
$query ="COMMIT;";
$conn->query($query);