1、登录
用管理员账号登录 mysql,在终端输入以下命令:
mysql -u root -p
"root”为管理员账号,输入命令后会提示输入密码,输入密码后按回车键进入 MySQL 系统
2、新增用户
create user 'username'@'host' identified by 'password';
"username" 是要创建的用户名,"host" 是该用户所能访问的主机地址, "password" 是该用户的密码。 如果需要用户可以从任何主机地址连接到 MySQL 服务器,需将将 "host" 设置为"%"。
例,新增用户名为 "testuser" 的用户:
create user 'testuser'@'%' identified by 'test123';
3、删除用户
drop user 'username'@'host';
"username" 是要删除的用户名,"host" 是该用户所能访问的主机地址。
例,删除用户名为 "testuser" 的用户:
drop user 'testuser'@'%';
4、修改密码
alter user 'username'@'host' identified by 'newpassword';
"username" 是要修改密码的用户名,"host" 是该用户所能访问的主机地址,"newpassword" 是该用户的新密码。
例,修改用户名为 "testuser" 的用户密码为 "newpassword":
alter user 'testuser'@'%' identified by 'newpassword';
mysql 8 以前版本
-- 修改当前账户的密码:
set password = password('新密码')
-- 修改其他用户的密码:
set password for '用户名'@'允许登录地址' = PASSWORD('新密码');
5、授权
grant privileges on database.table to 'username'@'host';
"privileges" 是用户所能执行的数据库操作,包括 select、insert、update、delete 等。 "database.table" 是用户所能访问的数据库和表,"username" 是该用户的用户名,"host" 是该用户所能访问的主机地址。
例,给用户名为 "testuser" 的用户授予 select 和 update 权限:
grant select, update on testdb.* to 'testuser'@'%';
6、回收权限
prvoke privileges on database.table from 'username'@'host';
"privileges" 是用户拥有的权限,"database.table" 是用户所能访问的数据库和表,"username" 是该用户的用户名,"host" 是该用户所能访问的主机地址。
例,回收用户名为 "testuser" 的用户 "update" 权限:
revoke privileges on testdb.* from 'testuser'@'%';
7、查看权限
show grants for 'username'@'host';
"username" 是要查看权限的用户名,"host" 是该用户所能访问的主机地址。
例,查看用户名为 "testuser" 的用户的权限:
show grants for 'testuser'@'%';
以上就是 mysql 设置用户及其权限的操作方法,通过这些命令,可以方便地管理数据库用户及其权限,保障数据库的安全性。