Friday, April 25, 2014

load data from csv file / text file or any external file

load data from csv file / text file or any external file
The LOAD DATA INFILE statement reads rows from a text file into a table.
LOAD DATA INFILE after using this command i am able to load all data/rows into a table, which is quite fast.

CREATE TABLE `emp` (
  `empno` decimal(4,0) NOT NULL,
  `ename` varchar(10) DEFAULT NULL,
  `job` varchar(9) DEFAULT NULL,
  `mgr` decimal(4,0) DEFAULT NULL,
  `hiredate` date DEFAULT NULL,
  `sal` decimal(7,2) DEFAULT NULL,
  `comm` decimal(7,2) DEFAULT NULL,
  `deptno` decimal(2,0) DEFAULT NULL,
  PRIMARY KEY (`empno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


---DAta in my csv file / text file
3369;SMITH;CLERK;7902;1980-12-17;800
4399;ALLEN;SALESMAN;7698;1981-02-20;1600
5321;WARD;SALESMAN;7698;1981-02-22;1250



TYPE - 1 user variable can be used
LOAD DATA INFILE 'D:/test.csv'
INTO TABLE emp
 COLUMNS TERMINATED BY ';'
LINES TERMINATED BY '\r\n'
(`empno`,`ename`,`job`,`mgr`,`hiredate`,`sal`)
set `comm` = 232 ,`deptno` = 20
Query OK, 3 rows affected (0.11 sec)
Records: 3  Deleted: 0  Skipped: 0  Warnings: 0



TYPE - 2
---DAta in my csv file / text file
3369;SMITH;CLERK;7902;1980-12-17;800;232;20
4399;ALLEN;SALESMAN;7698;1981-02-20;1600;232;20
5321;WARD;SALESMAN;7698;1981-02-22;1250;232;20

LOAD DATA INFILE 'D:/test.csv'
INTO TABLE emp
 COLUMNS TERMINATED BY ';'
LINES TERMINATED BY '\r\n';
Query OK, 3 rows affected (0.11 sec)
Records: 3  Deleted: 0  Skipped: 0  Warnings: 0


TYPE - 3 We can also use "IGNORE" in command it will ignore number of lines, after using below in command it will ignore firest line and will start insert from second.
In this case external file is same as above.
LOAD DATA INFILE 'D:/test.csv'
INTO TABLE emp
 COLUMNS TERMINATED BY ';'
LINES TERMINATED BY '\r\n'
IGNORE 1 lines;
Query OK, 2 rows affected (0.06 sec)
Records: 2  Deleted: 0  Skipped: 0  Warnings: 0


more info at :
http://dev.mysql.com/doc/refman/5.1/en/load-data.html

No comments:

Post a Comment

web stats