{"id":37,"date":"2021-01-12T09:01:51","date_gmt":"2021-01-12T09:01:51","guid":{"rendered":"https:\/\/veltzer.net:8890\/?p=37"},"modified":"2021-01-12T09:02:32","modified_gmt":"2021-01-12T09:02:32","slug":"altering-the-character-set-of-a-mysql-database","status":"publish","type":"post","link":"https:\/\/veltzer.net:8890\/altering-the-character-set-of-a-mysql-database\/","title":{"rendered":"Altering the character set of a MySQL database"},"content":{"rendered":"\n

It happens often that I forget to change the default character set of a database to utf8 and so find out late in the development cycle that many of my fields are based on non utf8 character sets (mostly latin1). Then I go in and modify each field in turn using ALTER TABLE [table] MODIFY [field name] [field type] CHARACTER SET [charset]<\/code>. After some digging I found the ALTER TABLE $TABLE CONVERT TO CHARSET [charset]<\/code> syntax which converted all fields in a table to a certain character set. I looked for a similar syntax to convert the entire database and found ALTER DATABASE<\/code> which, unfortunately, only changes the default character set and collation but does not affect the existing tables, fields or data.<\/p>\n\n\n\n

So here is a script that repeats ALTER TABLE \/ CONVERT TO<\/code> on each table in your database:<\/p>\n\n\n\n

#!\/bin\/bash\n \n# parameters...\nUSER='[your db user name]'\nPASS='[your db password]'\nDB='[your db]'\nCHARSET='[character set (utf8?)]'\nCOLLATION='[collation (utf8_unicode_ci?)]'\n \n# here we go...\nQUERY=\"SELECT table_name FROM information_schema.TABLES WHERE table_schema = '$DB';\"\nTABLES=$(mysql -u $USER --password=$PASS $DB --batch --skip-column-names --execute=\"$QUERY\")\nfor TABLE in $TABLES; do\n        echo \"ALTER TABLE $TABLE ......\"\n        mysql -u $USER --password=$PASS $DB -e \"ALTER TABLE $TABLE CONVERT TO CHARSET $CHARSET\"\n        #mysql -u $USER --password=$PASS $DB -e \"ALTER TABLE $TABLE CONVERT TO CHARSET $CHARSET COLLATE $COLLATION\"\ndone<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"

It happens often that I forget to change the default character set of a database to utf8 and so find out late in the development cycle that many of my fields are based on non utf8 character sets (mostly latin1). Then I go in and modify each field in turn using ALTER TABLE [table] MODIFY … <\/p>\n