Monday 21 March 2016

LOAD DATA INFILE statement in MySQL

Your script stops while fetch data from txt/csv file? Here is a MySQL feature to make this task faster. "LOAD DATA INFILE" statement::

The LOAD DATA INFILE statement reads rows from a text/CSV file into a table at a very high speed.

To write data from a table to a file, use SELECT ... INTO OUTFILE. To read the file back into a table, use LOAD DATA INFILE. The syntax of the FIELDS and LINES clauses is the same for both statements. Both clauses are optional, but FIELDS must precede LINES if both are specified.

SYNTAX to fetch data from CSV file:

$FILE_PATH = "test.csv";
$TABLE_NAME = "tablename";
$TABLE_FIELDS = "name,address";

'LOAD DATA LOCAL INFILE "$file_path"
            INTO TABLE "$table_name"
        FIELDS TERMINATED BY ","
        OPTIONALLY ENCLOSED BY "\"
        LINES TERMINATED BY "\n"
($TABLE_FIELDS)';

In the above example, your CSV file must contains 2 fields name and address and line terminated by "\n".

For more reference
http://dev.mysql.com/doc/refman/5.7/en/load-data.html

No comments:

Post a Comment