How can we export data to a CSV file along with columns heading as its first line?
Answers
Sometimes we need to export data into a CSV file whose name has a timestamp at which that file is created. It can be done with the help of MySQL prepared statement. To illustrate it we are using the following example:
Example
The queries in the following example will export the data from table ‘student_info’ to the CSV file having a timestamp in its name.
mysql> SET @time_stamp = DATE_FORMAT(NOW(),'_%Y_%m_%d_%H_%i_%s'); Query OK, 0 rows affected (0.00 sec) mysql> SET @FOLDER = 'C:/mysql/bin/mysql-files'; Query OK, 0 rows affected (0.00 sec) mysql> SET @FOLDER = 'C:/mysql/bin/mysql-files/'; Query OK, 0 rows affected (0.00 sec) mysql> SET @PREFIX = 'Student15'; Query OK, 0 rows affected (0.00 sec) mysql> SET @EXT = '.CSV'; Query OK, 0 rows affected (0.00 sec) 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';"); Query OK, 0 rows affected (0.00 sec) mysql> PREPARE stmt FROM @command; Query OK, 0 rows affected (0.00 sec) Statement prepared mysql> execute stmt; Query OK, 6 rows affected (0.07 sec)
The above query will create CSV file name ‘student_2017_12_10_18_52_46.CSV’ i.e. a CSV file with timestamp value, having the following data:
101;"YashPal";"Amritsar";"History" 105;"Gaurav";"Chandigarh";"Literature" 125;"Raman";"Shimla";"Computers" 130;"Ram";"Jhansi";"Computers" 132;"Shyam";"Chandigarh";"Economics" 133;"Mohan";"Delhi";"Computers"