Dump a mysql database to a plaintext (CSV) backup from the command line

前端 未结 10 1054
广开言路
广开言路 2020-11-28 19:26

I\'d like to avoid mysqldump since that outputs in a form that is only convenient for mysql to read. CSV seems more universal (one file per table is fine). But if there ar

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 19:33

    You can use below script to get the output to csv files. One file per table with headers.

    for tn in `mysql --batch --skip-page --skip-column-name --raw -uuser -ppassword -e"show tables from mydb"`
    do 
    mysql -uuser -ppassword mydb -B -e "select * from \`$tn\`;" | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' > $tn.csv
    done
    

    user is your user name, password is the password if you don't want to keep typing the password for each table and mydb is the database name.

    Explanation of the script: The first expression in sed, will replace the tabs with "," so you have fields enclosed in double quotes and separated by commas. The second one insert double quote in the beginning and the third one insert double quote at the end. And the final one takes care of the \n.

提交回复
热议问题