MySQL 是一个关系数据库管理系统,用于以表格格式存储数据。它为用户帐户和授予权限提供了高度的灵活性。
本教程将为您提供创建 MySQL 用户帐户和授予数据库权限的简短概述。
创建具有权限的MySQL用户
在这里,我们以对所有数据库拥有完全权限的 root 帐户运行所有查询。您可以创建具有所需权限的 MySQL 用户帐户。
- Let’s create a new MySQL user within MySQL shell:
mysql> CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'pa$$word';
Here newuser is the username to be created. The localhost is defines that this user is only accessible from localhost only. To connect MySQL from any remote host, change the localhost with remote system ip address. You can also use %
to allow any remote host to connect with this account.
- Now, assign the required privileges to the newly created MySQL user.
mysql> GRANT ALL ON *.* TO 'newuser'@'localhost';
阅读下一步以了解有关 mysql 帐户的各种授予选项的更多信息。
- After adding or modifying any privileges, make sur to reload the privilege’s to apply changes in running MySQL instance.
mysql> FLUSH PRIVILEGES;
授予 MySQL 用户权限
以下是在 MySQL 中为用户分配权限的常用选项。
-
ALL– 这将允许 mysql 用户完全访问指定数据库或完全访问所有数据库
-
SELECT– 允许用户从表中选择数据
-
INSERT– 允许用户将数据插入表中
-
UPDATE– 允许用户更新表中的数据
-
DELETE– 允许用户删除表中的行
-
CREATE– 允许用户创建新的数据库和表
-
DROP– 允许用户删除数据库和表
-
ALTER– 允许用户更改表的结构或在表上创建触发器。
-
授予选择权- 允许用户授予或删除其他用户权限
使用以下选项将特定数据库的所有权限授予 newuse@localhost。
mysql> GRANT ALL ON dbname.* TO 'newuser'@'localhost';
使用以下选项向 newuse@localhost 授予特定数据库的特定权限,例如 SELECT、INSERT、DELETE。
mysql> GRANT SELECT,INSERT,DELETE ON dbname.* TO 'newuser'@'localhost';
user@localhsot 对特定数据库的所有权限,包括授予其他用户的权限。
mysql> GRANT ALL ON dbname.* TO 'newuser'@'localhost' WITH GRANT OPTION;
您还可以查看MySQL中用户的允许权限。
mysql> SHOW GRANTS FOR 'newuser'@'localhost';
登录 MySQL Shell
使用新创建的用户和密码登录 MySQL shell。
mysql -u newuser -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 4817
Server version: 5.7.32-0ubuntu0.16.04.1 (Ubuntu)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>