How to convert date in .csv file into SQL format before mass insertion

风流意气都作罢 提交于 2019-12-05 12:05:21

Have you tried the following:

LOAD DATA LOCAL INFILE 'c:/scheduletest.csv' INTO TABLE game
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(@DATE_STR, `time`, `awayteam_id`, `hometeam_id`)
SET `date` = STR_TO_DATE(@DATE_STR, '%c/%e/%Y');

For more information, the documentation has details about the use of user variables with LOAD DATA (about half-way down - search for "User variables in the SET clause" in the page)

You can use variables to load the data from the csv into and run functions on them before inserting, like:

LOAD DATA INFILE 'file.txt'
INTO TABLE t1
(@datevar, @timevar, awayteam_id, hometeam_id)
SET date = STR_TO_DATE(@datevar, '%m/%d/%Y'),
SET time = etc etc etc;

My suggestion would be to insert the file into a temporary holding table where the date column is a character datatype. Then write a query with theSTR_TO_DATE conversion to move the data from the holding table to your final destination.

  1. Convert field that you are using for the date to varchar type so it will play friendly with any format

  2. Import CSV

  3. Convert the dates to a valid mysql date format using something like:

    UPDATE table SET field = STR_TO_DATE(field, '%c/%e/%Y %H:%i');
  1. Then revert field type to date

Use a function to convert the format as needed.

I'm not an expert on MySQL, but http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_str-to-date looks promising.

If you can't do that in the load command directly, you may try creating a table that allows you to load all the values as VARCHAR and then to do an insert into your game table with a select statement with the appropriate conversion instead.

If you file is not too big, you can use the Excel function TEXT. If, for example, your date is in cell A2, then the formula in a temporary column next to it would be =TEXT(A2,"yyyy-mm-dd hh:mm:ss"). This will do it and then you can paste the values of the formula's result back into the column and then delete the temporary column.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!