On this page
- 1 Insert data using a CSV file
- 2 Insert data using a CSV file
- 2.1 Update data based on another table
- 2.1.0.1 Connecting to a MySQL Database and Creating a Backup
- 2.1.0.2 SQL: Stored Procedure
- 2.1.0.3 SQL: Indexing in Databases
- 2.1.0.4 SQL: Joins (Inner, Left, Right and Full Joins)
- 2.1.0.5 SQL Transactions: BEGIN, COMMIT, ROLLBACK
- 2.1.0.6 Managing Duplicate Rows in SQL
- 2.1.0.7 Structured Query Language (SQL)
- 2.2 Leave A Comment Cancel reply
- 2.1 Update data based on another table
Insert data using a CSV file
Insert data using a CSV file
August 21, 2024
Insert data using a CSV file
LOAD DATA LOCAL INFILE '/var/www/html/csv_file/your_csv_file.csv' IGNORE INTO TABLE my_table fields terminated BY ',' lines terminated BY '\n' IGNORE 1 ROWS (@col1, @col2, @col3, @col4,, @col5) SET col1 = @col1, col2 = @col2, col3 = @col3, col4 = @col4, col5 = @col5
Let’s break down the code step by step:
LOAD DATA LOCAL INFILE '/var/www/html/csv_file/your_csv_file.csv'
:This part of the code specifies the path to the CSV file you want to load data from. In this example, the file path is ‘/var/www/html/csv_file/your_csv_file.csv’. TheLOCAL
keyword indicates that the file is located on the local file system of the MySQL client.INTO TABLE my_table
:This part of the code specifies the target database table where you want to insert the data. Replacemy_table
with the name of your actual MySQL table.FIELDS TERMINATED BY ','
:This part of the code specifies that the fields in the CSV file are separated by a comma (,
). This delimiter is used to split each line of the CSV file into individual columns.LINES TERMINATED BY '\n'
:This part of the code specifies that each line in the CSV file is terminated by a newline character (\n
). This indicates the end of a row in the CSV file.IGNORE 1 ROWS
:This optional part of the code tells MySQL to ignore the first row of the CSV file. This is often used when the first row contains headers and you don’t want to insert it as data.(@col1, @col2, @col3, @col4, @col5)
:This part of the code defines user variables@col1
,@col2
,@col3
,@col4
, and@col5
. These variables correspond to the columns in your MySQL table.SET col1 = @col1, col2 = @col2, col3 = @col3, col4 = @col4, col5 = @col5
:This part of the code sets the values of the table columns (col1
,col2
,col3
,col4
,col5
) to the values stored in the user variables (@col1
,@col2
,@col3
,@col4
,@col5
) for each row of data in the CSV file. This effectively maps the columns in the CSV file to the corresponding columns in the database table.
Update data based on another table
UPDATE table_1 INNER JOIN table_2 ON table_1.internal_id = table_2.internal_id SET table_1.city = table_2.city, table_1.state = table_2.state WHERE table_2.internal_id = table_2.internal_id