Java 應用透過 JDBC 向 MySQL 插入中文,資料庫欄位、表、庫皆設為 `utf8`/`utf8mb4`,但儲存後變為 `???` 或亂碼。
JDBC 驅動預設連線字符集非 UTF-8 (舊版為 `latin1`),連線層面未指定編碼,導致驅動以錯誤編碼將 Java `String` (UTF-16) 轉換為位元組送入 MySQL。
-- 錯誤範例 jdbc:mysql://localhost:3306/your_db -- 正確範例 (MySQL Connector/J 5.1+) jdbc:mysql://localhost:3306/your_db?useUnicode=true&characterEncoding=utf8mb4 -- 完整推薦參數 (生產環境) jdbc:mysql://localhost:3306/your_db?useUnicode=true&characterEncoding=utf8mb4&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
String url = "jdbc:mysql://localhost:3306/news?useUnicode=true&characterEncoding=utf8mb4&serverTimezone=UTC";
String user = "root";
String pass = "123";
Connection con = DriverManager.getConnection(url, user, pass);
// 或一次寫死
// Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/news?user=root&password=123&useUnicode=true&characterEncoding=utf8mb4");
try (PreparedStatement ps = con.prepareStatement("INSERT INTO test (content) VALUES (?)")) {
ps.setString(1, "測試中文 😀");
ps.executeUpdate();
}
// 資料庫查詢應正確顯示 "測試中文 😀"
資料庫設定 utf8mb4 只是儲存端正確;JDBC 連線字串必須加 `useUnicode=true&characterEncoding=utf8mb4` 才能保證傳輸端正確。 這是 Java 連 MySQL 中文亂碼 99% 的解藥。