Home > Database > Mysql Tutorial > How Can I Easily Import a CSV File into a MySQL Table Using SQL?

How Can I Easily Import a CSV File into a MySQL Table Using SQL?

Barbara Streisand
Release: 2024-12-16 03:03:09
Original
727 people have browsed it

How Can I Easily Import a CSV File into a MySQL Table Using SQL?

Import a CSV File into a MySQL Table with Ease

Importing a CSV file into a MySQL table is a practical task that can often arise in various data manipulation scenarios. This question-and-answer thread delves into the process, providing a solution that goes beyond relying on a GUI interface.

To initiate the import, it's crucial to transform an Excel file into a CSV format. Remember to remove any headers or empty data from the resulting CSV file.

Now, the import process can be executed using the following SQL syntax:

load data local infile 'uniq.csv' into table tblUniq fields terminated by ','
enclosed by '"'
lines terminated by '\n'
(uniqName, uniqCity, uniqComments)
Copy after login

This command reads the CSV file into the MySQL table named tblUniq, with each row representing a record and each field being separated by a comma (`,).

In cases where the CSV file contains a header row that should be used as column names, the following statement can be employed:

LOAD DATA LOCAL INFILE 'uniq.csv'
INTO TABLE tblUniq
FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(uniqName, uniqCity, uniqComments)
Copy after login

By skipping the first line (IGNORE 1 LINES), this command uses the data from the second row onwards to automatically create the table structure and assign column names.

Ultimately, this detailed explanation provides a comprehensive solution for importing CSV files into MySQL tables, addressing the user's specific requirement to use the first row of data as column names.

The above is the detailed content of How Can I Easily Import a CSV File into a MySQL Table Using SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template