Monday, November 26, 2018
How to output MySQL query results in CSV format?
Answer
Answer
Is there an easy way to run a MySQL query from the Linux command line and output the results in CSV format?
Here's what I'm doing now:
mysql -u uid -ppwd -D dbname << EOQ | sed -e 's/ /,/g' | tee list.csv
select id, concat("\"",name,"\"") as name
from students
EOQ
It gets messy when there are a lot of columns that need to be surrounded by quotes, or if there are quotes in the results that need to be escaped.
Answer
From http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/
SELECT order_id,product_name,qty
FROM orders
WHERE foo = 'bar'
INTO OUTFILE '/var/lib/mysql-files/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
Using this command columns names will not be exported.
Also note that /var/lib/mysql-files/orders.csv
will be on the server that is running MySQL. The user that the MySQL process is running under must have permissions to write to the directory chosen, or the command will fail.
If you want to write output to your local machine from a remote server (especially a hosted or virtualize machine such as Heroku or Amazon RDS), this solution is not suitable.
plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV
In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...
-
I need to do the following: My current address looks like: https://www.domain.com I want to redirect with htaccess: www.domain.com TO https:...
-
This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year. Unlike many other programm...
-
using namespace std; So far in my computer science courses, this is all we have been told to do. Not only that, but it's all tha...
No comments:
Post a Comment