SELECT...INTO OUTFILE導出數據到文件mysql
使用SELECT...INTO OUTFILE能夠導出數據到文件,同時指定每一個字段的分隔符和每行的換行符,以下,sql
mysql> select id, name, price from book into outfile '/tmp/book_data.txt' fields terminated by',' lines terminated by '\r\n'; Query OK, 4 rows affected (0.00 sec) mysql>
以下是文本中數據的格式,數據庫
1,Hello World,1.2 2,hello world book,1.2 3,hello world book,1.2 4,hello world book,1.2
能夠看到使用逗號來分隔每一個字段,換行符是\r\n。函數
但有時候登陸不到數據庫的主機上,能夠使用mysql -e命令導出咱們想要的數據,以下,code
➜ ~ mysql -h localhost -u root -p034039 -e 'select id, name, price from account.book' > book_data.txt mysql: [Warning] Using a password on the command line interface can be insecure.
其實這使用的Linux的IO重定向。打開文件,能夠看到以下數據,登錄
id name price 1 Hello World 1.2 2 hello world book 1.2 3 hello world book 1.2 4 hello world book 1.2
其實就是sql->select id, name, price from account.book的查詢結果,而後輸出到文件中的。 可是字段的分隔還不是很清晰明瞭,那怎麼辦? 能夠經過concat 函數鏈接多個字段爲一行,而後中間加上分隔符,這樣就清晰了,這樣寫sql,以下,file
➜ ~ mysql -h localhost -u root -p034039 -e 'select concat(id,"|",name,"|",price) from account.book' > book_data.txt mysql: [Warning] Using a password on the command line interface can be insecure.
輸出的文件格式爲:select
concat(id,"|",name,"|",price) 1|Hello World|1.2 2|hello world book|1.2 3|hello world book|1.2 4|hello world book|1.2
========END========command