搭建测试环境需要新建数据库进行权限分配
客户端工具可直接执行以下语句
create user 'testy'@'localhost' identified by '123qwe';
create user 'testy'@'%' identified by '123qwe';
flush privileges;
create database zzz_yun DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
grant all privileges on `zzz_yun`.* to 'testy'@'localhost' identified by '123qwe' with grant option;
grant all privileges on `zzz_yun`.* to 'testy'@'%' identified by '123qwe' with grant option;
flush privileges;
•all privileges:表示将所有权限授予给用户。也可指定具体的权限,如:SELECT、CREATE、DROP等。
•on:表示这些权限对哪些数据库和表生效,格式:数据库名.表名,这里写“*”表示所有数据库,所有表。如果我要指定将权限应用到test库的user表中,可以这么写:test.user
•to:将权限授予哪个用户。格式:”用户名”@”登录IP或域名”。%表示没有限制,在任何主机都可以登录。比如:”yangxin”@”192.168.0.%”,表示yangxin这个用户只能在192.168.0IP段登录
•identified by:指定用户的登录密码
•with grant option:表示允许用户将自己的权限授权给其它用户
也可以通过用命令执行
登录mysql
-
[root@xufeng Desktop]# mysql -u root -p
-
Enter password:
-
#创建新的用户
-
允许本地ip访问localhost的mysql数据库
-
mysql>create user 'testy'@'localhost' identified by '123qwe';
-
允许外网ip访问数据库testy,本命令包含上面的命令,是所有的ip都可以访问数据库
-
mysql>create user 'testy'@'%' identified by '123qwe';
- 刷新授权
-
mysql>flush privileges;
-
创建数据库zzz_yun
-
create database zzz_yun DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
-
将用户testy赋权给数据库zzz_yun,并刷新授权
grant all privileges on `zzz_yun`.* to 'testy'@'localhost' identified by '123qwe' with grant option;
grant all privileges on `zzz_yun`.* to 'testy'@'%' identified by '123qwe' with grant option;
flush privileges; -
用testy 密码123qwe登录数据库
用户详情的权限列表请参考MySQL官网说明:http://dev.mysql.com/doc/refman/5.7/en/privileges-provided.html
mysql> grant select,create,drop,update,alter on *.* to 'haha'@'localhost' identified by '123456' with grant option;
mysql> show grants for 'haha'@'localhost';
删除haha这个用户的create权限,该用户将不能创建数据库和表。
mysql> revoke create on *.* from 'haha@localhost';
mysql> flush privileges;
六、用户重命名
shell> rename user 'test3'@'%' to 'test1'@'%';
七、修改密码
1> 更新mysql.user表
1 2 3 4 5 6 |
|
2> 用set password命令
语法:set password for ‘用户名'@'登录地址'=password(‘密码')
mysql> set password for 'root'@'localhost'=password('123456');
3> mysqladmin
语法:mysqladmin -u用户名 -p旧的密码 password 新密码
mysql> mysqladmin -uroot -p123456 password 1234abcd
注意:mysqladmin位于mysql安装目录的bin目录下
八、忘记密码
1> 添加登录跳过权限检查配置
修改my.cnf,在mysqld配置节点添加skip-grant-tables配置
[mysqld]
skip-grant-tables
2> 重新启动mysql服务
shell> service mysqld restart
3> 修改密码
此时在终端用mysql命令登录时不需要用户密码,然后按照修改密码的第一种方式将密码修改即可。
4> 还原登录权限跳过检查配置
将my.cnf中mysqld节点的skip-grant-tables配置删除,然后重新启动服务即可。