Burco Burco - 2 months ago 14
MySQL Question

LOAD data infile not importing datetime

I have csv file which looks:


0,00018332,2016-08-29 00:00:00,2016-08-29 00:00:00,9999,Sale of Parts only,0,DMS Maritime Pty Ltd,xyz,,00000250,1971-01-01 00:00:00,1971-01-01 00:00:00,218335,Sale of parts only,9999


Then I have php script which is importing this csv into table

$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "test.csv";
$dbtable = "res";

$affectedRows = $pdo->exec("
LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$dbtable`
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
LINES TERMINATED BY ".$pdo->quote($lineseparator));


But when I check it back in db table, values 2016-08-29 00:00:00 (column is datetime) is 0000-00-00 00:00:00 , 218335 and 9999 is set to 0 event columns are set to int(11).Everything else is written correctly. I tried with csv and txt and I have same problem.

Do you know why?

EDIT:

CREATE TABLE `res` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text,
`start` datetime DEFAULT NULL,
`end` datetime DEFAULT NULL,
`room_id` int(11) DEFAULT NULL,
`status` varchar(30) DEFAULT NULL,
`paid` int(11) DEFAULT NULL,
`customer` varchar(50) DEFAULT NULL,
`name_ship` varchar(50) DEFAULT NULL,
`equipment` text,
`port` varchar(30) DEFAULT NULL,
`ETA` datetime DEFAULT NULL,
`ETD` datetime DEFAULT NULL,
`service_id` int(11) NOT NULL,
`service_classification` varchar(30) DEFAULT NULL,
`partners_id` int(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5392 DEFAULT CHARSET=latin1

Answer

Your file is encoded in utf16, mysql will not check that on its own. Either change that in your datasource (since your table encoding indicates that you don't want to use utf16 strings anyway) or inform mysql about the file's encoding.

For your file, the following should work:

LOAD DATA LOCAL INFILE 'test.csv' INTO TABLE res
CHARACTER SET utf16le
FIELDS TERMINATED BY ';\0'
LINES TERMINATED BY '\r\0\n\0';

It sets the characterset of the file and defines the delimiters in unicode. You can use just '\n\0' too.