Forums

Export mysql table as csv

I can't figure out how to do this, I was able to use the mysqldump command but I got a .sql file, I need something I can easily look at. Thank you!

Here you go: http://www.electrictoolbox.com/using-mysqldump-to-save-data-to-csv-files/

I'm trying this:

mysqldump -u seerk -h mysql.server -p -t -T/home/seerk/ 'seerk$rutdata' --fields-terminated-by=,

Getting error:

Access denied for user 'seerk'@'%' (using password: YES) when executing 'SELECT INTO OUTFILE'

Is it prompting you for a password? If so, are you sure you're entering the correct one? You should use your MySQL password, not the one you use to log in to PythonAnywhere.

Yes I'm sure, I get a different error if I enter a wrong password.

Ah, right -- got it. It looks like Glenn's suggestion above won't work, because the -T flag makes mysqldump try to write the file on the database server rather than locally into your PythonAnywhere file space. Let me take a look to see if there's a better way to do this.

Right, unfortunately I think you need to write your own SQL commands to do this. Here's something that worked for me (to dump the contents of a Django users table:

echo "select concat(id, ', ', username) from auth_user" | mysql -u MYUSERNAME -p -hmysql.server --skip-column-names 'MYUSERNAME$MYDBNAME'

It's a bit ugly, and (of course) it doesn't do the quoting you might want for a proper CSV. But if all you want is something human-readable, you should be able to hack something together. Perhaps even this would be more helpful:

echo "select id, username from auth_user" | mysql -u MYUSERNAME -p -hmysql.server --skip-column-names 'MYUSERNAME$MYDBNAME'

...or this:

echo "select id, username from auth_user" | mysql -u MYUSERNAME -p -hmysql.server 'MYUSERNAME$MYDBNAME'

Thanks that worked! Used:

echo "select concat(rut, ', ', data) from data where rut between 1 and 1000000" | mysql -u seerk -p -hmysql.server --skip-column-names 'seerk$rutdata' > dump.csv

Awesome, thanks for confirming!

There is an idea that can ease the export to csv: Just write a code in python to write a csv file from a "select" query on the db

that's true- writing a python script will certainly be easier if you intend to change the csv file fields etc/use this constantly over the long run.