Difficulty
Last Reviewed
Notes
Reference Link
Reviewed
Status
Tags
The procedure for importing a CSV file into MySQL is similar to PostgreSQL, but there are slight differences in commands and interface, particularly if you're using a tool like phpMyAdmin or the MySQL CLI. Here's how to achieve the same outcome in MySQL:
Step 1: Create the Database
- Log into MySQL:
- Create a database:
bash
CopyEdit
mysql -u root -p
sql
CopyEdit
CREATE DATABASE school;
USE school;
Step 2: Create the Tables
Run the following SQL script to create the tables (students, courses, and enrollments):
Step 3: Prepare the CSV Files
- Create CSV files for
students,courses, andenrollments. - Ensure each file matches the column structure of the respective table.
Example CSV file for students (students.csv):
csv
CopyEdit
first_name,last_name,email,date_of_birth
John,Doe,john.doe@example.com,2000-05-15
Jane,Smith,jane.smith@example.com,1999-08-20
Alice,Johnson,alice.johnson@example.com,2001-02-12
Step 4: Import the CSV Files
- Use the
LOAD DATA INFILEcommand to import the CSV file: - Repeat for
coursesandenrollments:
sql
CopyEdit
-- Import data into students table
LOAD DATA INFILE '/path/to/students.csv'
INTO TABLE students
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(first_name, last_name, email, date_of_birth);
Step 5: Verify the Data
Query each table to confirm the data has been imported:
sql
CopyEdit
SELECT * FROM students;
SELECT * FROM courses;
SELECT * FROM enrollments;
Key Notes for MySQL
- File Path:
- For
LOAD DATA INFILE, the file must be in a directory accessible to the MySQL server. - If the file is local, you can use
LOAD DATA LOCAL INFILEand enable-local-infileduring connection: - Permissions:
- Ensure the MySQL user has the required
FILEprivilege to access the file. - Error Handling:
- Use
SHOW WARNINGS;after runningLOAD DATA INFILEto troubleshoot import issues.
bash
CopyEdit
mysql --local-infile -u root -p