简体   繁体   English

在使用LOAD DATA INFILE的同时将CSV时间戳导入MySQL可接受的格式

[英]Import CSV timestamp into MySQL acceptable format while using LOAD DATA INFILE

I have a CSV file with the timestamp in the following format 我有一个带有以下格式的时间戳的CSV文件

 timestamp,             day_chan2, day_chan3
01/02/2014 00:00,             9,    2
01/02/2014 00:00,            16,    5

I am trying to import it into a MySQL database using LOAD DATA INFILE 我正在尝试使用LOAD DATA INFILE将其导入MySQL数据库

$query_name = "LOAD DATA INFILE ' "
                                . $file_path . 
                                "' INTO TABLE '"
                                . $this->table_name . 
                                 " ' FIELDS TERMINATED BY '\,' 
                                 LINES TERMINATED BY '\\n' 
                                 IGNORE 1 LINES 
                                 (`time_stamp`,`day_chan2`,`day_chan3`)";

My problem is the following: how do I convert the timestamp into a format acceptable to my MySQL while importing it into the database? 我的问题如下:将时间戳导入数据库时​​,如何将其转换为MySQL可接受的格式?

I am clueless now on how to change the timestamp into a proper timestamp which I can use to query later. 我现在对如何将时间戳更改为适当的时间戳一无所知,以后可以使用它进行查询。

I've never tried this, but you might be able to do something like: 我从没有尝试过,但是您可以执行以下操作:

$query_name = "LOAD DATA INFILE ' "
                                . $file_path . 
                                "' INTO TABLE '"
                                . $this->table_name . 
                                 " ' FIELDS TERMINATED BY '\,' 
                                 LINES TERMINATED BY '\\n' 
                                 IGNORE 1 LINES 
                                 (@mytimestamp,`day_chan2`,`day_chan3`)
                                 SET time_stamp=STR_TO_DATE(@mytimestamp, '%d/%m/%Y %h:%i');"

There are examples of this in the MySQL documentation: MySQL文档中有一些示例:

http://dev.mysql.com/doc/refman/5.1/en/load-data.html http://dev.mysql.com/doc/refman/5.1/en/load-data.html

MySQLs STR_TO_DATE is probably the best way to do this, given your comment, see below... 考虑到您的评论,MySQL STR_TO_DATE可能是执行此操作的最佳方法,请参见下文...

if (!($stmt = $mysqli->prepare("INSERT INTO ". $this->table_name . "(`time_stamp`,`day_chan2`,`day_chan3`) VALUES (STR_TO_DATE(?, 'd/m/y H:M'),?,?)"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
for ($fields in $data) {
   $stmt->bind_param('i', $fields[0]);
   $stmt->bind_param('i', $fields[1]);
   $stmt->bind_param('i', $fields[2]);
   if (!$stmt->execute()) {
      echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
   }
}

Good luck and leave a comment if you need further help. 祝您好运,如果您需要进一步的帮助,请发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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