MySQL修改字符集

2023-02-16  本文已影响0人  冷小冰Q

字符集级别

MySQL中默认字符集的设置有四级:

前三种均为默认设置,并不代表字段最终会使用这个字符集设置。

查询当前字符集

SHOW CREATE DATABASE db_name;
SHOW CREATE TABLE table_name;
SHOW FULL COLUMNS FROM table_name;
-- 或
SHOW FULL FIELDS FROM table_name; 

修改字符集

ALTER DATABASE db_name DEFAULT CHARACTER SET character_name [COLLATE ...];
ALTER TABLE table_name CONVERT TO CHARACTER SET character_name [COLLATE ...]
-- 示例:
ALTER TABLE cmpt_test CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE table_name DEFAULT CHARACTER SET character_name [COLLATE...];
-- 示例:
ALTER TABLE cmpt_test DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE table_name CHANGE f_name f_name CHARACTER SET character_name [COLLATE ...];
-- 示例:
ALTER TABLE cmpt_test CHANGE title title VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci;

组装SQL

SELECT DISTINCT
    CONCAT( "ALTER TABLE ", table_schema, ".", table_name, " CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" ) AS updateSql 
FROM
    information_schema.COLUMNS 
WHERE
    table_schema = 'db_name'
    AND COLLATION_NAME <> 'utf8mb4_unicode_ci';
SELECT
    CONCAT( "ALTER TABLE ", table_schema, ".", table_name, " CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" ) AS updateSql 
FROM
    information_schema.TABLES 
WHERE
    table_schema = 'db_name' 
    AND TABLE_COLLATION <> 'utf8mb4_unicode_ci';
上一篇下一篇

猜你喜欢

热点阅读