「庫、表、連接、應用」四層編碼必須保持一致。以 GB2312 為例(現代項目強烈建議統一使用 utf8mb4),完整配置鏈路如下:
CREATE DATABASE db_name DEFAULT CHARACTER SET gb2312;
String url = "jdbc:mysql://" + host + "/" + dbName
+ "?user=" + user
+ "&password=" + password
+ "&useUnicode=true&characterEncoding=gb2312";
useUnicode=true 告知驅動程式啟用字符集轉換;characterEncoding 指定目標編碼,驅動會自動將 Java 內部 Unicode 轉為 GB2312 傳給數據庫。
response.setContentType("text/html");
response.setCharacterEncoding("GB2312");
確保瀏覽器正確解碼頁面輸出,避免「存進去正常、取出來亂碼」的現象。
utf8mb4,連接串改為 characterEncoding=utf-8,並設置 connectionCollation=utf8mb4_unicode_ci。my.cnf / my.ini 中 [client]、[mysql]、[mysqld] 區塊的 default-character-set 是否一致。SHOW VARIABLES LIKE 'character%'; 驗證運行時實際生效的字符集設置。