我的数据库不是UTF8,我想将所有表转换为UTF8,我该怎么做?
对于单个表,您可以执行以下操作:
ALTER TABLE tab CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
对于整个数据库,我不知道除此之外的其他方法:
http://www.commandlinefu.com/commands/view/1575/convert-all-mysql-tables-and-fields-to-utf8
mysqldump --user=username --password=password --default-character-set=latin1 --skip-set-charset dbname > dump.sql
sed -r 's/latin1/utf8/g' dump.sql > dump_utf.sql
mysql --user=username --password=password --execute="DROP DATABASE dbname; CREATE DATABASE dbname CHARACTER SET utf8 COLLATE utf8_general_ci;"
mysql --user=username --password=password --default-character-set=utf8 dbname < dump_utf.sql
用您的数据库名称替换my_database_name
SELECT CONCAT('ALTER TABLE ', TABLE_NAME, ' CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'my_database_name' AND TABLE_TYPE != 'VIEW';
这将构建许多可以运行的查询
更好的是,使用Percona的工具包。我会在更新到utf8mb4之前审核您的索引,因为密钥长度存在问题。
SELECT CONCAT('pt-online-schema-change --alter "CONVERT TO CHARACTER SET utf8
COLLATE utf8_unicode_ci" t=', TABLE_NAME, ',D=DB_NAME,u=USER_NAME --statistics --execute')
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'DB_NAME' AND TABLE_TYPE != 'VIEW' AND TABLE_COLLATION NOT LIKE '%utf8%';