Exporting MySQL SQL Results to CSV Without Using INTO OUTFILE
Overview
When you want to export the results of a MySQL SELECT statement to CSV,
you can do so by running the following on the CLI.
1 | $ mysql -u <user> -p<password> <db_name> |
However, if the MySQL login user
the output fails with an error like the following.
1 | RROR 1 (HY000): Can't create/write to file '/tmp/output.csv' (Errcode: 13) |
Granting READ/WRITE permission via the FILE privilege would solve the problem,
but there are times when you would rather not touch privileges.
On a production DB where the privileges are a black box,
you might break into a cold sweat worrying that running FLUSH PRIVILEGES could cause some kind of outage.
Below I’ve summarized what I did in such a situation.
The Idea
The approach is to first export the results as a TXT file,
then process it into a CSV file with sed.
Example) Suppose you obtain a SQL result like the following
1 | $ less output.txt |
↓ After processing it so it displays nicely in Excel
1 | $ less output.txt |
Procedure
Output the query result to output.txt
1 | $ mysql -u <user> -p<password> <db_name> -e"<query>" > output.txt |
Process it for Excel
- Brute force
1 | // Prepend a `"` at the very beginning of each line (`^`) |
Change the Character Encoding
Match the character encoding to that used by the recipient of this CSV.
The recipient said Shift JIS was their default, so I converted it accordingly.
1 | $ nkf -g output4.txt |
1 | $ nkf -sLw output4.txt > output.csv |
With this, I was able to obtain a CSV file without using INTO OUTFILE.
ouput.csv
Bonus
Add a date to the file name.
1 | $ mv output.csv output_`date '+%Y%m%d'`.csv |
1 | $ ls |
Exporting MySQL SQL Results to CSV Without Using INTO OUTFILE
https://kenzo0107.github.io/en/2016/03/14/mysql-output-csv-without-outfile/
