How can I import a CSV file into a MySQL table? I would like for the first row of data be used as the column names.
I read How do I import CSV file into a MySQL table?, but the only answer was to use a GUI and not a shell?
Instead of writing a script to pull in information from a CSV file, you can link MYSQL directly to it and upload the information using the following SQL syntax.
To import an Excel file into MySQL, first export it as a CSV file. Remove the CSV headers from the generated CSV file along with empty data that Excel may have put at the end of the CSV file.
You can then import it into a MySQL table by running:
load data local infile 'uniq.csv' into table tblUniq fields terminated by ',' enclosed by '"' lines terminated by '\n' (uniqName, uniqCity, uniqComments)
as read on: Import CSV file directly into MySQL
For your case, you’ll need to write an interpreter first, for finding the first row, and assigning them as column names.
From MySQL docs on
LOAD DATA syntax:
IGNORE number LINESoption can be used to ignore lines at the
start of the file. For example, you can use
IGNORE 1 LINESto skip
over an initial header line containing column names:
LOAD DATA INFILE '/tmp/test.txt' INTO TABLE test IGNORE 1 LINES;
Therefore, you can use the following statement:
LOAD DATA LOCAL INFILE 'uniq.csv' INTO TABLE tblUniq FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES (uniqName, uniqCity, uniqComments)
Answered By – hjpotter92
Answer Checked By – Jay B. (BugsFixing Admin)