MySQL 批量修改數據表編碼及字符集

當須要修改數據庫編碼和字符集時,一般須要對其下屬的全部表及表中全部字段進行修改。如下備註批量修改方案( 以修改成 utf8mb4_bin 爲例,注意將 db_name 換爲真實的數據庫名 )。

1. 修改數據庫編碼及字符集

這一步比較簡單,直接執行便可:mysql

ALTER DATABASE db_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin;

2. 修改數據表與表中字段的編碼及字符集

這裏須要兩步。sql

首先,須要利用語句,生成全部實際執行的語句:數據庫

SELECT 
CONCAT("ALTER TABLE `", TABLE_NAME,"` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;") 
AS target_tables
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="db_name"
AND TABLE_TYPE="BASE TABLE"

此語句會基於 MySQL 的元數據表,獲得一組可直接執行的 SQL 列表,以下:編碼

ALTER TABLE `table1` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
ALTER TABLE `table2` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
ALTER TABLE `table3` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
ALTER TABLE `table4` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
ALTER TABLE `table5` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
ALTER TABLE `table6` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;

其中,table1table6 即爲數據庫中的全部數據表。code

而後,直接將語句粘貼並執行便可。server

注意,這裏使用 CONVERT TO 而非 DEFAULT,是由於後者不會修改表中字段的編碼和字符集。utf-8

此外,對於數據表比較多的數據庫,能夠先將第一步的執行結果導出到 .sql 文件,再經過該 SQL 文件執行便可。get

參考連接

  1. mysql - Difference between database, table, column collation - Stack Overflow
  2. automation - Alter charset and collation in all columns in all tables in MySQL - Server Fault
  3. character encoding - How to convert an entire MySQL database characterset and collation to UTF-8? - Stack Overflow
  4. mysql - How to convert all tables in database to one collation? - Stack Overflow
  5. How to easily convert utf8 tables to utf8mb4 in MySQL 5.5 - Database Administrators Stack Exchange
  6. MySQL case insensitive select - Stack Overflow
  7. Character Set and Collation Overview - MariaDB Knowledge Base
相關文章
相關標籤/搜索