简体   繁体   中英

How to export a CSV file from the MySQL command line

I have a MySQL database containing a single table which is used as a temporary storage point for manipulating and querying data sets and is periodically deleted and replaced with new data. What I would like to be able to do is export the data from the MySQL command line to use for other purposes. I am using the XAMPP Apache server package with phpMyAdmin on Windows 10.

The issue I am having is the INTO OUTFILE syntax I am using returns an error relating to '\\n'. Below is an example of the syntax:

SELECT *  
FROM tablename  
WHERE work_complete = 'Yes' 
INTO OUTFILE 'C:\file path for the file to be exported to\file_name.csv'   
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY "''"   
ESCAPED BY '\'  
LINES TERMINATED BY '\n'; 

I have spent some time researching this without any luck, I have even tried using

LINES TERMINATED BY '\r\n'

but the error remained the same

ERROR: Unknown command '\''.
   ->     LINES TERMINATED BY '\r\n';

If anyone could provide any tips that would be greatly appreciated.

The problem is not in LINES TERMINATED BY but in ESCAPED BY .

This:

ESCAPED BY '\'  

Is invalid syntax, because the backslash is interpreted as an escape character for the following quote. A decent text editor should let you see that.

You need to escape the backslash, like so:

ESCAPED BY '\\'  

Alternatively, you can also use '\\b' :

ESCAPED BY '\b'  

Another probem is that OPTIONALLY ENCLOSED accepts only a single character, while you are giving it two single quotes.

In your query:

SELECT *  FROM tablename WHERE work_complete = 'Yes' 
INTO OUTFILE 'C:\file path for the file to be exported to\file_name.csv'   
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY "'" ESCAPED BY '\\'  
LINES TERMINATED BY '\n'

Use this

SELECT *  
FROM tablename  
#WHERE work_complete = 'Yes' 
INTO OUTFILE 'C:\file path for the file to be exported to\file_name.csv'   
FIELDS ENCLOSED BY '"' 
TERMINATED BY ';' 
ESCAPED BY '"' 
LINES TERMINATED BY '\r\n';

I used some other syntax as you and deleted the OPTIONALLY which mysql doesn't like at that place

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM