Question

I have 35 CSV files which I want to import to MYSQL table(say 'test'). I want to create one column in 'test' table( say 'file_name'). This column will contain name of the CSV from which data has been imported. The file names are unique IDs, that is why I want to get file name as input in the table.

Suppose I have CSV files like X1.csv, X2.CSV, X3.csv .... X35.csv. I want a column in 'test' table as 'file_name' such that 'test' table looks something like:


col1 -> a, b, c, d

col2 -> x, y, w, z

... ...

... ....

file_name -> X1, X1, X2, X3


Note: I tried to search this question on forum but I could not find any suitable solution. Also I am new to MYSQL, please help even it is a trivial thing.

Was it helpful?

Solution

I'm not sure this is exactly what you are looking for, but at first sight, you should investigate the LOAD DATA INFILE statement:

LOAD DATA INFILE 'X1.csv' INTO TABLE tbl_name -- Load the content of the CSV file
  FIELDS TERMINATED BY ',' ENCLOSED BY '"'    -- assuming fields separate by ",", enclosed by "'"
  LINES TERMINATED BY '\r\n'                  -- assuming end-of-line being '\r\n'
  IGNORE 1 LINES                              -- assuming first line is a header and should be ignored
  SET file_name = 'X1';                       -- force the column `file_name` to be the name of the file

Please note that with such statement, each field will go in its own column of the table. And each line of the CSV data file will be loaded a one row in the table. This will imply that there will be several rows in the result table with the same file name. In fact one row per data line.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top