Cover Image for MySQL Import CSV File in Database
98 views

MySQL Import CSV File in Database

To import a CSV file into a MySQL database, you can use the LOAD DATA INFILE statement. This statement allows you to read data from a CSV file and insert it into a MySQL table. Here’s how to do it:

1. Prepare Your CSV File:
Ensure that your CSV file is correctly formatted, with a header row (column names) and data rows. Make sure that the column order in the CSV file matches the column order in the target MySQL table.

2. Create a MySQL Table:
You need to create a MySQL table that matches the structure of the CSV file. You can use the CREATE TABLE statement to do this. Here’s an example:

   CREATE TABLE mytable (
       id INT,
       name VARCHAR(255),
       age INT
   );

Replace mytable with the name of your table and define the appropriate columns and data types.

3. Load Data from CSV:
Use the LOAD DATA INFILE statement to import data from the CSV file into the MySQL table. Here’s an example:

   LOAD DATA INFILE '/path/to/your/file.csv'
   INTO TABLE mytable
   FIELDS TERMINATED BY ','
   ENCLOSED BY '"'
   LINES TERMINATED BY '\n'
   IGNORE 1 LINES;  -- Skip the header row
  • Replace /path/to/your/file.csv with the full path to your CSV file.
  • Replace mytable with the name of your MySQL table.
  • Adjust the FIELDS TERMINATED BY, ENCLOSED BY, and LINES TERMINATED BY clauses to match the CSV file’s format. In this example, the CSV is comma-separated and enclosed by double quotes, with lines terminated by a newline character.
  • IGNORE 1 LINES is used to skip the header row if your CSV file has one.

4. Verify the Data:
After executing the LOAD DATA INFILE statement, check the table to ensure that the data from the CSV file has been successfully imported.

5. Adjust Table and Data Types:
If the data types in your CSV file do not match the table’s data types, you may need to make adjustments to ensure data integrity.

Remember to have the necessary file and table permissions to perform these operations. Additionally, the LOAD DATA INFILE statement may not work in some hosting environments due to security restrictions, so you might need to consider alternative methods in such cases.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS