Home > Database > Mysql Tutorial > body text

How to Save MySQL Query Output to Excel or .txt File?

DDD
Release: 2024-11-05 20:38:02
Original
724 people have browsed it

How to Save MySQL Query Output to Excel or .txt File?

Saving MySQL Query Output to Excel or .txt File

To save the output of a MySQL query to a Microsoft Excel or .txt file, you can utilize the following methods:

Using INTO OUTFILE

MySQL provides the INTO OUTFILE syntax to easily export query results to a text file on the server. It allows you to create comma-separated value (CSV) files suitable for import into spreadsheets.

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.txt'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
Copy after login

This query will generate a tab-separated file with each row on a separate line. You can modify the output format by setting field terminators, enclosures, and line separators.

Using a Client Output Redirection

Alternatively, you can execute the query from your local client and redirect the output to a local file:

mysql -user -pass -e "select cols from table where cols not null" > /tmp/output
Copy after login

This approach captures the query output to a local file named "output" in the "/tmp" directory.

Tips

  • Ensure that the output file does not exist before executing the query.
  • MySQL must have write permissions to the directory where the file is being saved.
  • If an absolute path is not specified, the output file will be stored in the directory specified by SHOW VARIABLES LIKE 'datadir';.

The above is the detailed content of How to Save MySQL Query Output to Excel or .txt File?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template