Skip to content

Instantly share code, notes, and snippets.

@samuelpismel
Created November 9, 2015 13:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save samuelpismel/f41c3e7ec7861f39bf59 to your computer and use it in GitHub Desktop.
Save samuelpismel/f41c3e7ec7861f39bf59 to your computer and use it in GitHub Desktop.
Shell script to change and convert mysql databases charset and collate.
#!/bin/bash
database='database'
user='user'
pass='pass'
charset='utf8mb4'
collate='utf8mb4_unicode_ci'
echo "Changing charset of database: $database"
mysql -u $user -p$pass $database -s -e "ALTER DATABASE $database CHARACTER SET = $charset COLLATE = $collate;"
for table in $(mysql $database -s --skip-column-names -e 'show tables')
do
echo ''
echo "Changing charset of table: $table"
mysql -u $user -p$pass $database -s -e "ALTER TABLE $table CHARACTER SET $charset COLLATE $collate"
echo "Converting charset of table: $table"
mysql -u $user -p$pass $database -s -e "ALTER TABLE $table CONVERT TO CHARACTER SET $charset COLLATE $collate"
done
echo ''
echo 'Conversion done!'
echo ''
echo 'Optimizing tables...'
echo ''
mysqlcheck -u $user -p$pass $database --auto-repair --optimize
echo ''
echo 'Done! Have a nice day! ;)'
@frankmflynn
Copy link

Nice - you might have to add "SET FOREIGN_KEY_CHECKS=0;" to line 20 so it reads:
mysql -u $user -p$pass $database -s -e "SET FOREIGN_KEY_CHECKS=0;ALTER TABLE $table CONVERT TO CHARACTER SET $charset COLLATE $collate"
If your database has foreign keys that are characters (like uuid or names) you will get an error "Cannot change column 'uuid': used in a foreign key constraint..." Although not usual in traditional SQL where you would always use int for keys in lots of newer stuff uuid is becoming popular.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment