Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store MySQL results to a file in table format

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
like image 968
OutOfBoundsException Avatar asked Jan 08 '13 21:01

OutOfBoundsException


People also ask

How do you output MySQL query results to a file?

Save MySQL Results to a File There's a built-in MySQL output to file feature as part of the SELECT statement. We simply add the words INTO OUTFILE, followed by a filename, to the end of the SELECT statement. For example: SELECT id, first_name, last_name FROM customer INTO OUTFILE '/temp/myoutput.

How do I save SQL query output to a file?

Click Query, and then click Results to File. Enter and then execute the SQL statement. In the Save Results dialog box, specify the following settings: Save In: Select a directory in which to save the file.

Which statement can you use to load data from a file into a table?

The LOAD DATA statement reads rows from a text file into a table at a very high speed. The file can be read from the server host or the client host, depending on whether the LOCAL modifier is given.


1 Answers

This should do the trick:

mysql -u root -p -t -vvv < select.sql | sed '1 d' > output.txt
like image 132
GreyBeardedGeek Avatar answered Sep 29 '22 17:09

GreyBeardedGeek