Exporting table from Amazon RDS into a csv file

前端 未结 6 1377
后悔当初
后悔当初 2020-11-29 17:43

I have a mysql database running in Amazon RDS, and I want to know how to export an entire table to csv format. I currently use mysql server on Windows to query the Amazon da

6条回答
  •  悲&欢浪女
    2020-11-29 18:22

    Assuming MySQL in RDS, an alternative is to use batch mode which outputs TAB-separated values and escapes newlines, tabs and other special characters. I haven't yet struck a CSV import tool that can't handle TAB-separated data. So for example:

    $ mysql -h myhost.rds.amazonaws.com -u user -D my_database -p --batch --quick -e "SELECT * FROM my_table" > output.csv
    

    As noted by Halfgaar above, the --quick option flushes immediately so avoids out-of-memory errors for large tables. To quote strings (recommended), you'll need to do a bit of extra work in your query:

    SELECT id, CONCAT('"', REPLACE(text_column, '"', '""'), '"'), float_column
      FROM my_table
    

    The REPLACE escapes any double-quote characters in the text_column values. I would also suggest using iso8601 strings for datetime fields, so:

    SELECT CONCAT('"', DATE_FORMAT(datetime_column, '%Y%m%dT%T'), '"') FROM my_table
    

    Be aware that CONCAT returns NULL if you have a NULL column value.

    I've run this on some fairly large tables with reasonable performance. 600M rows and 23GB data took ~30 minutes when running the mysql command in the same VPC as the RDS instance.

提交回复
热议问题