MySQLdump – the safe way

event 23 Nov 2017 account_circle Nicolas
label_outline Bash SQL

Dumping and importing from/to MySQL in an UTF-8 safe way

In a nutshell: to avoid your shell character set from messing with imports, use -r to export and SOURCE when importing.

Dumping safely

[pastacode lang= »bash » manual= »%23%20Do%20not%20do%20this%2C%20since%20it%20might%20screw%20up%20encoding%0Amysqldump%20-uroot%20-p%20database%20%3E%20utf8.dump%20%23%20this%20is%20bad » message= » » highlight= » » provider= »manual »/]

Better do:

[pastacode lang= »bash » manual= »mysqldump%20-uroot%20-p%20database%20-r%20utf8.dump » message= » » highlight= » » provider= »manual »/]

Note that when your MySQL server is notset to UTF-8 you need to do mysqldump --default-character-set=latin1 (!) to get a correctly encoded dump. In that case you will also need to remove the SET NAMES='latin1' comment at the top of the dump, so the target machine won’t change its UTF-8 charset when sourcing.

If you only want to dump the structure without data, use

[pastacode lang= »bash » manual= »mysqldump%20-uroot%20-p%20–no-data%20database%20-r%20utf8.dump » message= » » highlight= » » provider= »manual »/]

Importing a dump safely

[pastacode lang= »bash » manual= »%23%20Do%20not%20do%20this%2C%20since%20it%20might%20screw%20up%20encoding%20%0Amysql%20-u%20username%20-p%20database%20%3C%20dump_file%20%23%20this%20is%20bad%20″ message= » » highlight= » » provider= »manual »/]

Better do:

[pastacode lang= »bash » manual= »mysql%20-uroot%20-p%20–default-character-set%3Dutf8%20database%20%0Amysql%3E%20SET%20names%20’utf8’%20%0Amysql%3E%20SOURCE%20utf8.dump » message= » » highlight= » » provider= »manual »/]