如何将csv中的日期字符串数据加载到mysql数据库?
How to load data of string of date in csv to mysql database?
这是我的 .csv 文件的一瞥:
Name,Start Date,End Date,Budget
Class 1,1/1/2020,31/1/2020,"USD10,000.00"
Class 2,1/2/2020,28/2/2020,"USD14,000.00"
csv 中的日期格式为 %e/%c/%Y
.
我正在尝试将此数据加载到 table class
,这是我所做的:
LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/class.csv'
INTO TABLE class
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(class_name, @start_date, @end_date, @budget)
SET start_date = REPLACE(@start_date, '/', '-'),
end_date = REPLACE(@start_date, '/', '-'),
budget = REPLACE(@budget, 'USD', ''),
budget = REPLACE(@budget, ',', '');
但是returns
Error Code: 1292.
Incorrect date value: '1-1-2021' for column 'start_date' at row 1
如何处理?
看来你需要使用STR_TO_DATE()
函数,例如
SET start_date = STR_TO_DATE(@start_date, '%d/%m/%Y')
as start_date
是一个 DATE 类型的列,而不是一个普通的字符串。据推测,相同的逻辑也适用于end_date
。
这是我的 .csv 文件的一瞥:
Name,Start Date,End Date,Budget
Class 1,1/1/2020,31/1/2020,"USD10,000.00"
Class 2,1/2/2020,28/2/2020,"USD14,000.00"
csv 中的日期格式为 %e/%c/%Y
.
我正在尝试将此数据加载到 table class
,这是我所做的:
LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/class.csv'
INTO TABLE class
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(class_name, @start_date, @end_date, @budget)
SET start_date = REPLACE(@start_date, '/', '-'),
end_date = REPLACE(@start_date, '/', '-'),
budget = REPLACE(@budget, 'USD', ''),
budget = REPLACE(@budget, ',', '');
但是returns
Error Code: 1292. Incorrect date value: '1-1-2021' for column 'start_date' at row 1
如何处理?
看来你需要使用STR_TO_DATE()
函数,例如
SET start_date = STR_TO_DATE(@start_date, '%d/%m/%Y')
as start_date
是一个 DATE 类型的列,而不是一个普通的字符串。据推测,相同的逻辑也适用于end_date
。