How to store MySQL results to a file in table format

最后都变了- 提交于 2019-11-30 04:19:48

问题


I am trying to create a file and store in it the results from my query. I have a batch file that contains the single query,

USE database1;

SELECT * FROM table WHERE name = "abc" INTO OUTFILE output.txt;

QUIT

Executing this batch file using,

mysql -u root -p -t -vvv < select.sql

However, the result is not table formatted and fields' names are missing from the top.

100 abc Brown 32
101 abc Flair 25
102 abc McDonald 45
.
.
.

If I remove the INTO OUTFILE statement and print the results on terminal, then is working OK.

+----+------+---------+-----+
| id | name | surname | age |
+----+------+---------+-----+
| 100| abc  | Brown   |   32|
| 101| abc  | Flair   |   25|
| 102| abc  | McDonald|   45|
+----+------+---------+-----+

How can I achieve the above in a txt file?

UPDATE

Special thanks to GreyBeardedGeek. Here is the solution for this question with help of GreyBeardedGeek.

Batch file:

USE database1;

SELECT * FROM table WHERE name = "abc";

QUIT

and mysql client:

mysql -u root -p -t -vvv < select.sql > output.txt

回答1:


This should do the trick:

mysql -u root -p -t -vvv < select.sql | sed '1 d' > output.txt



回答2:


You can also do following:

mysql -uroot -p DatabaseName -t -e "select * from table" > file.txt

This doesn't need to make an SQL file and then filter out the first line.




回答3:


Besides using mysql client program options (mysql --help) one can configure defaults within .my.cnf file. Example (MacOs, Linux) to enable --table option:

edit/create a file:

vim ~/.my.cnf

add/update:

[client]
table

next time you call mysql command line program it will use options from .my.cnf file producing output in table format, e.g. the same as one has called:

mysql ... --table ... 

Please note that command line options override options from the .my.cnf files.

References:

  • call mysql --help for list of options
  • https://dev.mysql.com/doc/refman/8.0/en/option-files.html


来源:https://stackoverflow.com/questions/14224240/how-to-store-mysql-results-to-a-file-in-table-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!