How to Import Data into MySQL from a CSV File

How to Import Data into MySQL from a CSV File

To import data into MySQL from a CSV file, you can use the LOAD DATA INFILE statement. Here are the steps:

Step 1: Prepare Your CSV File

Make sure your CSV file is properly formatted and contains the data you want to import. Ensure that the columns in the CSV file match the columns in the MySQL table.

Step 2: Access MySQL Shell

Open your terminal or command prompt and log in to MySQL using the following command:

Bash
mysql -u username -p

Replace username with your MySQL username. You’ll be prompted for your MySQL password.

Step 3: Select the Database (If Not Already Selected)

If you haven’t already selected a database, use the USE command to select the database you want to import data into:

SQL
USE database_name;

Replace database_name with the name of the database.

Step 4: Run the LOAD DATA INFILE Command

Use the LOAD DATA INFILE statement to import data from the CSV file. Assuming your CSV file is named data.csv and your table is named your_table, the command would be:

SQL
LOAD DATA INFILE 'path/to/data.csv'
INTO TABLE your_table
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
  • Replace path/to/data.csv with the actual path to your CSV file.
  • Replace your_table with the name of the table you want to import into.

Explanation of options:

  • FIELDS TERMINATED BY ',': Specifies that the fields in the CSV file are separated by commas.
  • ENCLOSED BY '"': Indicates that fields are enclosed by double quotes.
  • LINES TERMINATED BY '\n': Specifies that lines in the CSV file are terminated by a newline character.
  • IGNORE 1 ROWS: Skips the first row of the CSV file (assuming it contains headers).

Step 5: Verify the Import

You can check if the data was imported correctly by querying the table:

SQL
SELECT * FROM your_table;

Replace your_table with the name of your table.

Step 6: Exit MySQL Shell

To exit the MySQL shell, type:

SQL
EXIT;

You’ve successfully imported data from a CSV file into a MySQL table. You can continue to perform other operations on your data as needed.

Total
0
Shares

Leave a Reply

Previous Post
How to Restore a MySQL Database Backup

How to Restore a MySQL Database Backup

Next Post
How to Export Data from MySQL to a CSV File

How to Export Data from MySQL to a CSV File

Related Posts