Home >Database >Mysql Tutorial >How to Programmatically Import CSV Files into MySQL Despite Column Name Differences?
When importing CSV files into MySQL, it's common to encounter discrepancies in column names between the CSV and the database table. Fortunately, MySQL provides a convenient solution for such scenarios.
To programmatically import a CSV file into a database with different column names, you can use the LOAD DATA INFILE syntax with a specified column list. This allows you to map specific CSV columns to their corresponding database columns.
For example, the following code imports data from a CSV file named "uniq.csv" into a table called "tblUniq":
String query = "LOAD DATA INFILE 'uniq.csv' INTO TABLE tblUniq ( uniqName, uniqCity, uniqComments ) fields terminated by ',' enclosed by '\"' lines terminated by '\n';";
In this query, the first three fields from the CSV file are mapped to the corresponding columns in the database table.
You can also specify a custom column list, as shown in the following example:
String query = "LOAD DATA INFILE 'uniq.csv' INTO TABLE tblUniq ( uniqName, uniqState, uniqPhone ) fields terminated by ',' enclosed by '\"' lines terminated by '\n';";
Here, the CSV columns are mapped to different columns in the database table, allowing you to handle discrepancies in column names with ease.
The above is the detailed content of How to Programmatically Import CSV Files into MySQL Despite Column Name Differences?. For more information, please follow other related articles on the PHP Chinese website!