MySQL 创建数据库

用 CREATE DATABASE 建库,并理解字符集与排序规则。

Beginner
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.

Friends & Partners