一、MySQL 服务管理(必背)
bash
# 启动
systemctl start mysqld
# 停止
systemctl stop mysqld
# 重启
systemctl restart mysqld
# 开机自启
systemctl enable mysqld
# 状态
systemctl status mysqld
二、登录 & 基础命令
1. 登录
bash
mysql -uroot -p
2. 查看库
sql
show databases;
3. 进入库
sql
use 库名;
4. 查看表
sql
show tables;
5. 查看用户
sql
select user,host from mysql.user;
6. 创建用户
sql
create user 'test'@'%' identified by '123456';
7. 授权
sql
grant all on *.* to 'test'@'%';
flush privileges;
8. 改密码
sql
alter user 'root'@'localhost' identified by '新密码';
三、MySQL 启动不了?万能排查流程
1. 先看状态
bash
systemctl status mysqld
2. 直接看错误日志(90% 问题看这里)
bash
# 常见路径
tail -f /var/log/mysqld.log
tail -f /var/log/mysql/error.log
3. 最常见 5 大启动故障 & 解决
① 端口 3306 被占用
报错:Address already in use
bash
netstat -tulpn | grep 3306
kill -9 进程ID
② 磁盘满了
报错:Disk full
bash
df -h
清理日志、大文件。
③ 权限错误(最常见)
报错:Can't create/write to file
bash
chown -R mysql:mysql /var/lib/mysql
chmod -R 755 /var/lib/mysql
④ my.cnf 配置写错
bash
mysqld --help --verbose | grep my.cnf
改错配置直接起不来。
⑤ 内存不够
报错:Out of memory
bash
free -h
减小 innodb_buffer_pool_size。
四、忘记 root 密码怎么办?
- 免密码启动
bash
systemctl stop mysqld
mysqld_safe --skip-grant-tables &
- 登录改密
bash
mysql
use mysql;
update user set authentication_string=password('新密码') where user='root';
flush privileges;
quit;
- 正常重启
bash
systemctl restart mysqld
五、直接背的口诀
- 起不来 → 看日志
- 连不上 → 端口 / 防火墙 / 权限
- 权限错 → chown mysql:mysql
- 忘密码 → –skip-grant-tables