撒拉嘿哟木头 2008-12-10 15:59 采纳率: 100%
浏览 535
已采纳

如何以 CSV 格式输出 MySQL 查询结果?

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.

转载于:https://stackoverflow.com/questions/356578/how-to-output-mysql-query-results-in-csv-format

  • 写回答

29条回答 默认 最新

  • larry*wei 2008-12-10 16:07
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(28条)

报告相同问题?

悬赏问题

  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services