有时我们需要将数据导出到CSV文件中,该文件的名称带有创建该文件的时间戳。可以借助MySQL准备语句来完成。为了说明这一点,我们使用以下示例-
例
以下示例中的查询会将数据从表'student_info'导出到名称为时间戳的CSV文件。
mysql> SET @time_stamp = DATE_FORMAT(NOW(),'_%Y_%m_%d_%H_%i_%s'); mysql> SET @FOLDER = 'C:/mysql/bin/mysql-files'; mysql> SET @FOLDER = 'C:/mysql/bin/mysql-files/'; mysql> SET @PREFIX = 'Student15'; mysql> SET @EXT = '.CSV'; mysql> SET @Command = CONCAT("SELECT * FROM Student_info INTO OUTFILE '",@FOLDER, @PREFIX, @time_stamp, @EXT,"' FIELDS ENCLOSED BY '\"' TERMINATED BY ';' ESCAPED BY '\"'"," LINES TERMINATED BY '\r\n';"); mysql> PREPARE stmt FROM @command; Statement prepared mysql> execute stmt;
上面的查询将创建CSV文件名'student_2017_12_10_18_52_46.CSV',即带有时间戳值的CSV文件,具有以下数据-
101;"YashPal";"Amritsar";"History" 105;"Gaurav";"Chandigarh";"Literature" 125;"Raman";"Shimla";"Computers" 130;"Ram";"Jhansi";"Computers" 132;"Shyam";"Chandigarh";"Economics" 133;"Mohan";"Delhi";"Computers"