MySQL 转 csv,将mysql查询结果转换为CSV(使用复制/粘贴)

I often work in command line mysql. A common need is to take a query's results and import them into a Numbers document (similar to an Excel document).

What is the fastest method for doing this?

Method 1: Select into outfile

You can select into an outfile directly from MySQL, but this takes several steps.

export your query with all the necessary arguments to make it a CSV format, like FIELDS OPTIONALY ENCLOSED BY and DELIMITED BY.

sftp into the server and grab the file

delete the file from the server

Method 2: Copy/paste

I tend to do this method. For me it seems a little faster but that's mostly because I don't remember how to construct the SELECT INTO OUTFILE query from above and have to look it up.

Copy/paste to a local text file

Open in a text editor and replace | with ,

Save as a CSV and open in Numbers.

解决方案

How about this?:

mysql -b -e "$MY_QUERY" > my_data.csv

The output format is actually tab-separated rather than comma-separated

but at least Excel and OpenOffice Calc automatically adapt to this.

BTW, for convenience and to enable non-interactive execution of

mysql commands, I strongly recommend setting up a secure ~/.my.cnf file

(readable only by you) with entries like this:

[client]

user=YOUR_MYSQL_USER_NAME

password=YOUR_MYSQL_PASSWORD

host=YOUR_MYSQL_SERVER

port=YOUR_MYSQL_SERVER_PORT

WHATEVER_OTHER_OPTIONS_YOU_LIKE

References:

--batch, -B

Print results using tab as the column separator, with each row on a new line. With this option, mysql does not use the history file.

Batch mode results in nontabular output format and escaping of special characters. Escaping may be disabled by using raw mode; see the description for the --raw option.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值