用户的作用: 允许你所创建的用户对自己的数据库进行远程连接和操作

1. 用户的管理

  • 查看所有用户

select user from mysql.user;


  • 创建用户

# create user '用户名'@'IP地址' identified by '密码';

create user 'Kevin'@'192.168.0.250' identified by '123';  # 指定ip地址是因为只能允许那一台电脑上的用户能对mysql服务端进行链接

create user 'Kevin'@'192.168.0.%' identified by '123';  # 192.168.0.% 表示的是允许以 192.168.0 开头的ip地址能对mysql服务端进行链接

create user 'Kevin'@'192.168.%' identified by '123';  # 192.168.0.% 表示的是允许以 192.168 开头的ip地址能对mysql服务端进行链接

create user 'Kevin'@'%' identified by '123';  # 一个 % 表示不限制ip地址,允许所有用户名为Kevin的电脑能对mysql服务端进行链接


  • 删除用户

# drop user '用户名'@'IP地址';

drop user 'Kevin'@'192.168.0.150';  # 删除ip地址为 192.168.0.150 的用户

drop user 'Kevin'@'192.168.0.%';  # 192.168.0.% 表示删除以 192.168.0 开头的ip地址的用户

drop user 'Kevin'@'%';  # 一个 % 表示不限制ip地址,删除名为Kevin的用户


  • 修改用户名

# rename user '用户名'@'IP地址' to '新用户名'@'IP地址';

rename user 'Kevin'@'192.168.0.150' to 'Yeung'@'192.168.0.150';  # 将ip地址为 192.168.0.150 的用户名修改成 Yeung

rename user 'Kevin'@'192.168.0.%' to 'Yeung'@'192.168.0.%';  # 将以 192.168.0 开头的ip地址的用户名修改成 Yeung

rename user 'Kevin'@'%' to 'Yeung'@'%';  # 一个 % 表示不限制ip地址,将名为Kevin的用户名修改为Yeung


  • 修改密码

# set password for '用户名'@'IP地址' = Password('新密码');

set password for 'Kevin'@'192.168.0.150' = '456';  # 将名为 Kevin 的用户, 且ip地址是 192.168.0.150 的密码修改成 456

set password for 'Kevin'@'192.168.0.%' = '456';  # 将名为 Kevin 的用户, 且ip地址是以 192.168.0 开头的密码修改成 456

set password for 'Kevin'@'%' = '456';  # 一个 % 表示不限制ip地址,将名为 Kevin 的用户的密码修改成 456


2.用户授权管理

  • 创建完用户后需要对该用户进行授权,否则只是能远程连接进入数据库,而不能对数据库进行操作

  • 查看用户权限

# show grants for '用户'@'IP地址';

show grants for 'Kevin'@'%';

  • 授权 -> 添加用户权限

# grant 权限 on 数据库.表 to '用户'@'IP地址';

grant select,insert,update on db1.t1 to 'Kevin'@'%';  # 只允许该用户在 db1 数据库中的 t1 表使用 select insert update 权限

grant all privileges on db1.t1 to 'Kevin'@'%';  # 允许该用户在 db1 数据库中的 t1 表使用所有权限

grant all privileges on *.* to 'Kevin'@'%';  # 允许该用户对所有数据库中的所有表使用所有权限

  • 刷新授权表,使得权限立即生效 -> 对用户授权完后,需要刷新授权表,否则该用户不能立即获得你设置的权限

flush privileges;
用户名@IP地址
用户只能在改IP下才能访问
用户名@192.168.1.%
用户只能在改IP段下才能访问(通配符%表示任意)
用户名@%
用户可以再任意IP下访问(默认IP地址为%)


数据库名.*
指定数据库中的所有表
数据库名.表
指定数据库中的某张表
数据库名.存储过程
指定数据库中的存储过程
*.*
所有数据库和所有数据库下的表


权限
说明
all privileges
除grant外的所有权限
usage

alter

alter routine

create

create routine

create temporary tables

create user

create view

delete

drop

execute

file

grant option

index

insert

lock tables

process

select

show databases

show view

update

reload

shutdown

super

replication client

replication slave