Java insert Mysql中文字亂碼問題

Posted in :

這個連線時,要設定utf8編碼格式有關。

     Connection mConn

     try {
         Class.forName("com.mysql.jdbc.Driver").newInstance();
         mConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name?useUnicode=true&characterEncoding=utf-8", "root", "password");
     } catch (Exception e) {
        e.printStackTrace();
     }

環境是:

  • Rocky linux 8.6
  • mysql Ver 8.0.30 for Linux on x86_64
  • java openjdk 19.0.2 2023-01-17

在 create table 時有指定:

 ENGINE=InnoDB DEFAULT CHARSET=utf

結果還是亂碼.

如果修改 Connector/J 的 url 加入 &characterEncoding=utf8mb4 會掛掉, 無法連線.

Connector/J did not support utf8mb4 for servers 5.5.2 and newer.
Connector/J now auto-detects servers configured with character_set_server=utf8mb4 or treats the Java encoding utf-8 passed using characterEncoding=… as utf8mb4 in the SET NAMES= calls it makes when establishing the connection. (Bug #54175)

透過 sql command 檢查編碼:

show variables like 'character%';

-- SHOW VARIABLES LIKE 'collation_%';

結果, 在 mysql 裡顯示是正確的… , 原來是輸出時 browser 的問題, browser 不知道內容的編碼, 所以沒猜到是中文. 在 servlet 裡指定輸出為 utf-8 後, 就一切正常了.

response.setCharacterEncoding("UTF-8");

附註: 這個 response.setCharacterEncoding(“UTF-8”); 要在一進 protected void doPost() or doGet() 就呼叫, 如果是在最後才設定, 在設定之前輸出的, 也會是亂碼! 真是太神奇了.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *