Mysql的用户管理与授权

Mysql用户管理

  • 本人使用的是Mysql8.0的版本,可能会有一些语句不兼容;

1.用户管理

image-20211118093414128

  • 在Mysql中支持创建账户,并给账户分配权限;例如只拥有数据库A操作的权限、只拥有数据库B中某些表的权限,只拥有数据库B中某系表的读取权限

1.1 查询用户

  • 使用安装后产生的mysql库中的user表;查询对应的值,其中host是允许连接地址,远程连接的时候通常配置为%
  • image-20211118172534299

1.2用户管理

  • 创建用户
    -- 语法
    create user '用户名'@'连接者的IP地址' identified by '密码'
    
  • image-20211118173329560

  • 修改用户
    -- 语法
    rename user '用户'@'密码' to '新用户名'@'ip地址'
    
    
  • -- 修改用户
    rename user 'testuser'@'localhost' to 'whj'@'localhost';
    
  • image-20211118184032337

  • image-20211118184537191

  • 修改密码
    -- 语法
    set password for '用户名'@'IP' = Password('新密码');
    -- 修改密码
    set password for 'whj'@'localhost' = Password('XXXXX');
    
  • 笔记截图
  • image-20211118094537994

2.授权管理

  • 创建好用户之后,就可以为用户进行授权了

  • 授权
    grant 权限 on 数据库.表 to '用户@'ip地址'
    
  • grant all privileges on testlearn.* to 'whj'@'localhost'; -- 赋予一个库的所有权限
    
  • image-20211118185901248

  • 执行完成之后发现,用户whj只有一个库的使用权限,并且不能够创建新的数据库;

  • grant all privileges on *.* to 'whj'@'localhost'; -- 拥有数据库的所有权限
    grant all privileges on testlearn.student   'whj'@'localhost';  -- 用户拥有student表的所有权限
    grant select privileges on testlearn.student to 'whj'@'localhost'; --用户拥有student表的查询权限
    grant select,insert privileges on testlearn.* to 'whj'@'localhost'; -- 拥有数据库testlearn所有表的插入和修改权限
    
  • 每次授予权限之后需要刷新一下权限FLUSH PRIVILEGES;

  • image-20211118095021375

  • image-20211118095144289

  • 查看授权
  • --语法格式
    show grants for '用户'@'ip地址'
    
    -- 查看权限
    show grants for 'whj'@'localhost';
    
  • image-20211118191624544

  • image-20211118191316641

  • 取消授权
    -- 语法格式
    revoke 权限 on 数据库.表 from '用户'@'ip地址'
    
    revoke all PRIVILEGES on test.* from 'whj'@'localhost';
    

    image-20211118191943317

  • image-20211118095423370

3.整体代码

-- select user,authentication_string,host from user;

-- 创建用户
CREATE user 'testuser'@'localhost' IDENTIFIED by '123456';
-- 查看创建后的用户
select user,authentication_string,host from user;
-- 修改用户
rename user 'testuser'@'localhost' to 'whj'@'localhost';
-- 修改密码
-- set password for 'whj'@'localhost' = Password('1234567');

-- === 授权管理
grant all privileges on testlearn.* to 'whj'@'localhost';
-- 一般执行完成授权之后需要进行权限的刷新
FLUSH PRIVILEGES;

grant all privileges on test.* to 'whj'@'localhost';

FLUSH PRIVILEGES;

-- 查看权限
show grants for 'whj'@'localhost';

-- 取消授权
revoke all PRIVILEGES on test.* from 'whj'@'localhost';
FLUSH PRIVILEGES;

注:一般在公司,数据库的管理由DBA同一执行;

posted @ 2021-11-18 19:26  紫青宝剑  阅读(89)  评论(0编辑  收藏  举报