Converting a MySQL database to UTF-8
Converting a MySQL database to UTF-8
This article explains how to convert a MySQL database’s character set to UTF-8 (Unicode), which supports many alphabets and characters for various languages. Many databases use the Latin character set by default, which can be limiting.
Determining the current character encoding set
Section titled “Determining the current character encoding set”- Log in to your account via SSH:
mysql -u username -pEnter your password when prompted.
- To check the character set for a database (replace
dbnamewith your database name):
SELECT default_character_set_nameFROM information_schema.SCHEMATA SWHERE schema_name = "dbname";- To check the character set for a specific table (replace
dbnameandtablename):
SELECT CCSA.character_set_nameFROM information_schema.`TABLES` T, information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSAWHERE CCSA.collation_name = T.table_collation AND T.table_schema = "dbname" AND T.table_name = "tablename";- To exit MySQL:
\qConverting the character encoding set to UTF-8
Section titled “Converting the character encoding set to UTF-8”Warning: Back up your database before starting!
- Log in via SSH.
- Create a
.my.cnffile for login credentials:
nano .my.cnfAdd the following, replacing username and password:
[client]user=usernamepassword="password"Press Ctrl+X, then y to save, and Enter.
- Convert all tables in the database to UTF-8:
mysql --database=dbname -B -N -e "SHOW TABLES" | awk '{print "SET foreign_key_checks = 0; ALTER TABLE", $1, "CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; SET foreign_key_checks = 1; "}' | mysql --database=dbname- Start MySQL:
mysql- Convert the database itself to UTF-8:
ALTER DATABASE dbname CHARACTER SET utf8 COLLATE utf8_general_ci;- Exit MySQL:
\q- Remove the
.my.cnffile:
rm .my.cnf- Verify the character set is now UTF-8 by repeating the steps in the Determining the current character encoding set section.