lab/note/随手记/mysql的字符集坑.md

23 lines
1.3 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# MySQL 字符集的终极巨坑 —— `utf8` vs `utf8mb4`
### 一句话总结
MySQL 中的 `utf8` 是个“假货”(最多只支持 3 字节),`utf8mb4` 才是真正的 UTF-8支持 4 字节)。
### 为什么会有这个坑
- **历史遗留**:早期 MySQL 开发时Unicode 字符确实只用 3 个字节就能存下。
- **现象**:一旦用户输入 **Emoji 表情**(如 😀)或部分**生僻字**(如 𰻝),数据库会直接抛出错误:`Incorrect string value`。
### 📊 核心对比
| 字符集 | 真实身份 | 最大字节数 | 能否存 Emoji | 状态 |
| :------------ | :----------------- | :--------- | :----------- | :--------- |
| **`utf8`** | `utf8mb3` (阉割版) | 3 字节 | ❌ 报错 | ⚠️ 已废弃 |
| **`utf8mb4`** | 真正的 UTF-8 | 4 字节 | ✅ 随便存 | ✅ 推荐使用 |
### 🛠️ 各版本现状与未来
- **MySQL 5.7 及以前**:默认字符集是 `latin1``utf8` 是重灾区。
- **MySQL 8.0 及以后****默认字符集已改为 `utf8mb4`**(新项目安全系数提升)。
- **官方态度**:目前 `utf8`(即 `utf8mb3`)已被标记为 Deprecated废弃。官方计划在**未来的某个大版本中彻底删除 `utf8mb3`**,并让 `utf8` 这个名字正式指向 `utf8mb4`