简体   繁体   中英

Import .CSV into MySQL DB

I have a script that I am using to import .CSV data into a MySQL DB. The first field of data (email address) still has quote marks around it when I pull into MySQL. The other fields, the quotes are stripped out.

My CSV lines looks like this:

"email4@email.com"," Karla","Smith"

"email5@email.com"," Carl","Nichols"

The email addresses still have quotes in MySQL. The first and last name are fine.

Any suggestions?

<?php 

$conn = mysql_connect('host','username','password'); 

mysql_select_db('db-name'); 

mysql_query("TRUNCATE TABLE contacts") or die(mysql_error()); 

mysql_query("LOAD DATA LOCAL INFILE 'New Member Weekly Report for Marketing.csv' 
INTO TABLE contacts 
Fields terminated by ',' ENCLOSED BY '\"' 
LINES terminated by '\r'( 
contact_email 
,contact_first 
,contact_last)") 

or die("Import Error: " . mysql_error()); 
?>

On a little bit of googling, I found this:

Instead of writing a script to pull in information from a CSV file, you can link MYSQL directly to it and upload the information using the following SQL syntax.

To import an Excel file into MySQL, first export it as a CSV file. Remove the CSV headers from the generated CSV file along with empty data that Excel may have put at the end of the CSV file. You can then import it into a MySQL table by running:

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

The fields here are the actual tblUniq table fields that the data needs to sit in. The enclosed by and lines terminated by are optional and can help if you have columns enclosed with double-quotes such as Excel exports, etc.

Source: http://www.tech-recipes.com/rx/2345/import_csv_file_directly_into_mysql/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM