我创建了一个名为 StatesandCities 的表,其中有3列: CountryCode (它是一个外键), State 和 City < / em>,如下所示:
create table StatesandCities (CountryCode varchar(2), State varchar(20), city varchar(20),foreign key (CountryCode) references ListOfCountries (CountryCode));
我有一个包含所有值的.CSV文件:
CountryCode,State,City
IN,Karnataka,Bangalore
IN,Karnataka,Mysore
IN,Karnataka,Tumkur
IN,Maharashtra,Mumbai
IN,Maharashtra,Thane
IN,Maharashtra,Nasik
GB,Yorkshire,County Hill
GB,SouthWales,Murrey
这正是它在Excel工作表中的表现:
CountryCode State City
IN Karnataka Bangalore
IN Karnataka Mysore
IN Karnataka Tumkur
IN Maharashtra Mumbai
IN Maharashtra Thane
IN Maharashtra Nasik
GB Yorkshire County Hill
GB SouthWales Murrey
我使用此代码在MySQL 5.6命令行客户端中输入CSV文件:
LOAD DATA LOCAL INFILE 'H:/Statesncities.csv' INTO TABLE StatesandCities FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' ignore 1 lines (CountryCode, State, City);
正在输入值,但它们不是我需要的正确表格格式。而且如果数据值很长就会被削减。这一切都搞混了: 我试过改变屏幕大小,页面布局,似乎没什么用。
输出:
答案 0 :(得分:1)
试试这个:
LOAD DATA LOCAL INFILE 'H:/countries.csv' INTO TABLE ListOfCountries
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES (CountryName, CountryCode);
我正在使用IGNORE 1 LINES
来跳过CSV标题行。我也可以选择FIELDS ENCLOSED BY
。
您可以参考MySQL手册的LOAD DATA INFILE Syntax部分了解更多详情。
答案 1 :(得分:0)
this should do it !!
BULK INSERT mycountry
FROM 'C:\CSVmydata\country.csv'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = ',', --CSV field delimiter
ROWTERMINATOR = '\n', --Use to shift the control to next row
ERRORFILE = 'C:\CSVmydata_error\countryErrorRows.csv',
TABLOCK
)