跳至主要內容

MySQL配置

知识库数据库MySQLMySQL大约 3 分钟

MySQL 密码安全策略

-- 查看MySQL密码策略
SHOW VARIABLES LIKE 'validate_password%';
-- mysql5.7以后对密码的强度是有要求的,必须是字母+数字+符号组成的,如果想设置简单密码例 如‘root’,需要做以下设置
-- 设置密码长度最低位数 默认是8位
set global validate_password_length=4;
-- 设置密码强度级别 默认是1,可选 [LOW:0| MEDIUM:1 | STRONG:2]
set global validate_password_policy=0;
-- 设置最少数字数量 默认是1
set global validate_password_number_count=1;
-- 设置最少符号数量 默认是1
set global validate_password_special_char_count=1;
-- 修改root密码
alter user 'root'@'localhost' identified by 'root';
flush privileges;

MySQL 远程连接授权

------------------------
-- ALL PRIVILEGES :表示授予所有的权限,此处可以指定具体的授权权限。
-- *.* :表示所有库中的所有表
-- 'root'@'%' :myuser是数据库的用户名,%表示是任意ip地址,可以指定具体ip地址。
-- IDENTIFIED BY 'mypassword' :mypassword是数据库的密码。
-- WITH GRANT OPTION :这个选项表示该用户可以将自己拥有的权限授权给别人
------------------------
-- 授予root用户对所有数据库对象的全部操作权限
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root' WITH GRANT OPTION;
-- 创建一个admin用户,密码为admin
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED BY 'admin';
-- 关闭授权
REVOKE ALL ON *.* FROM 'admin'@'localhost';
-- 刷新权限
FLUSH PRIVILEGES;
-- 查看root权限为所有ip都可以访问
SHOW GRANTS FOR 'root'@'localhost';

MySQL 其他命令

-- 查看MySQL密码策略
SHOW VARIABLES LIKE 'validate_password%';
-- 显示数据库编码
show variables like 'char%';
-- 查看日志配置信息
show variables like 'log_%';
-- 查看MySQL数据文件
SHOW VARIABLES LIKE '%datadir%';
-- 显示用户正在运行的线程
show processlist;
-- 查看存储引擎
show engines;
-- 查看上次查询成本开销
show status like 'Last_query_cost';
-- 查看优化器的执行计划
explain select * from customer where customer_id=14;

mysql 密码忘记

  1. 启动 mysql 时不启动授权表功能,可以直接免密码登录
# 修改/etc/my.cnf文件
vim /etc/my.cnf
# 在[mysqld]区域添加配置,并保存my.cnf文件
skip-grant-tables

# 重启mysql
systemctl restart mysqld
# 登录mysql,如果出现输入密码,直接回车,就可以进入数据库了
mysql -u root -p
  1. 修改 root 密码
# 登录mysql,此时还没有进入数据库,使用如下命令
use mysql;

# (mysql5.6版本)修改root密码
update user set password=password('密码') where user='root';

# (mysql5.7版本)修改root密码
update user set authentication_string = password('密码'), password_expired = 'N',password_last_changed = now() where user = 'root';

# (mysql8版本)将root密码置空,废弃user表中password()方法,所以旧方法重置密码对mysql8.0版本是行不通的!
update user set authentication_string = '' where user = 'root';
# (mysql8版本)执行第三步,以无密码进入,设置root密码
ALTER USER 'root'@'localhost' IDENTIFIED BY 'Root@123456';

# 使其生效
flush privileges;
# 退出
exit;
  1. 重启服务器
    上面操作完成之后,其实还没有完,需要关闭授权表功能,重启服务器
# 修改/etc/my.cnf文件
vim /etc/my.cnf
# 在[mysqld]区域删除改配置,并保存my.cnf文件
# skip-grant-tables

# 重启mysql
systemctl restart mysqld