MySQL 创建数据库
用 CREATE DATABASE 建库,并理解字符集与排序规则。
Key Points建库时指定 utf8mb4 与 utf8mb4_0900_ai_ci,能避免绝大部分中文乱码。
基本语法
SQL
CREATE DATABASE shop
CHARACTER SET utf8mb4
COLLATE utf8mb4_0900_ai_ci;Output
Query OK, 1 row affected (0.01 sec)先看再建,避免报错
SQL
-- 不存在才建
CREATE DATABASE IF NOT EXISTS shop
DEFAULT CHARACTER SET utf8mb4;
-- 列出所有库
SHOW DATABASES;
-- 看某个库的建库语句
SHOW CREATE DATABASE shop;Output
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| shop |
| sys |
+--------------------+字符集与排序规则
The charset decides which characters you can store; the collation decides how they compare and sort. utf8mb4 is real UTF-8 (emoji included); utf8mb4_0900_ai_ci is MySQL 8.0's accent-insensitive, case-insensitive ordering.
MySQL's
utf8 is a 3-byte subset and cannot store emoji. Always use utf8mb4 for new projects.基本语法
SQL
CREATE DATABASE shop
CHARACTER SET utf8mb4
COLLATE utf8mb4_0900_ai_ci;Output
Query OK, 1 row affected (0.01 sec)先看再建,避免报错
SQL
-- 不存在才建
CREATE DATABASE IF NOT EXISTS shop
DEFAULT CHARACTER SET utf8mb4;
-- 列出所有库
SHOW DATABASES;
-- 看某个库的建库语句
SHOW CREATE DATABASE shop;Output
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| shop |
| sys |
+--------------------+字符集与排序规则
字符集(charset) 决定能存哪些字符,排序规则(collation) 决定如何比较和排序。utf8mb4 是真正的 UTF-8(含 emoji),utf8mb4_0900_ai_ci 表示 8.0 的、不区分重音(ai)、不区分大小写(ci) 的排序。
MySQL 的
utf8 是阉割版(最多 3 字节,存不了 emoji 和部分生僻字)。新项目一律用 utf8mb4。