如何将整个MySQL数据库字符集转换为UTF-8和排序为UTF-8?
当前回答
Make a backup! Then you need to set the default char sets on the database. This does not convert existing tables, it only sets the default for newly created tables. ALTER DATABASE dbname CHARACTER SET utf8 COLLATE utf8_general_ci; Then, you will need to convert the char set on all existing tables and their columns. This assumes that your current data is actually in the current char set. If your columns are set to one char set but your data is really stored in another then you will need to check the MySQL manual on how to handle this. ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
其他回答
Make a backup! Then you need to set the default char sets on the database. This does not convert existing tables, it only sets the default for newly created tables. ALTER DATABASE dbname CHARACTER SET utf8 COLLATE utf8_general_ci; Then, you will need to convert the char set on all existing tables and their columns. This assumes that your current data is actually in the current char set. If your columns are set to one char set but your data is really stored in another then you will need to check the MySQL manual on how to handle this. ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
如果你不能让你的表转换,或者你的表总是设置为一些非utf8字符集,但你想要utf8,你最好的办法可能是擦掉它,重新开始,并显式地指定:
create database database_name character set utf8;
命令行解决方案和排除视图
我只是在为像我和布莱恩这样在我们的数据库中有视图的人完成@Jasny的回答。
如果你有这样的错误:
ERROR 1347 (HY000) at line 17: 'dbname.table_name' is not of type 'BASE TABLE'
这是因为你可能有自己的观点,你需要排除它们。 但是当试图排除它们时,MySQL返回2列而不是1列。
SHOW FULL TABLES WHERE Table_Type = 'BASE TABLE';
-- table_name1 BASE TABLE
-- table_name2 BASE TABLE
因此,我们必须用awk修改Jasny的命令,只提取包含表名的第一列。
DB="dbname"
(
echo 'ALTER DATABASE `'"$DB"'` CHARACTER SET utf8 COLLATE utf8_general_ci;'
mysql "$DB" -e "SHOW FULL TABLES WHERE Table_Type = 'BASE TABLE'" --batch --skip-column-names \
| awk '{print $1 }' \
| xargs -I{} echo 'ALTER TABLE `'{}'` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;'
) \
| mysql "$DB"
简单复制/粘贴的一行程序
DB="dbname"; ( echo 'ALTER DATABASE `'"$DB"'` CHARACTER SET utf8 COLLATE utf8_general_ci;'; mysql "$DB" -e "SHOW FULL TABLES WHERE Table_Type = 'BASE TABLE'" --batch --skip-column-names | awk '{print $1 }' | xargs -I{} echo 'ALTER TABLE `'{}'` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;' ) | mysql "$DB"
使用HeidiSQL。它是免费的,而且是一个非常好的数据库工具。
从工具菜单,进入批量表编辑器
选择完整的数据库或选择表进行转换,
tick更改默认排序规则:utf8mb4_general_ci tick转换为字符集:utf8
执行
这将在短短几秒钟内将完整的数据库从拉丁语转换为utf8。
工作就像一个魅力:)
HeidiSQL默认连接为utf8,因此任何特殊字符现在都应该被视为字符(æ ø å),而不是在检查表数据时被编码。
从latin到utf8的真正陷阱是确保pdo与utf8字符集连接。如果不是,你会得到垃圾数据插入到utf8表和问号在你的网页上到处都是,让你认为表数据不是utf8…
你也可以使用数据库工具Navicat,这样做更容易。
湿 婆。
右键单击您的数据库,并在下拉菜单中选择数据库属性和更改