# 用户权限管理

用户权限管理：在不同的项目中给不同的角色（开发者）不同的操作权限，为了保证数据库数据的安全。

通常，一个用户的密码不会长期不变，所以需要经常性的变更数据库用户密码来确保用户本身安全（mysql客户端用户）

## 1、用户管理

Mysql需要客户端进行连接认证才能进行服务器操作：需要用户信息。Mysql中所有的用户信息都是保存在mysql数据库下的user表中。

```
mysql> select * from mysql.user\G
```

默认的，在安装Mysql的时候，如果不选择创建匿名用户，那么意味着所有的用户只有一个：root超级用户

```
mysql> desc mysql.user;
+--------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field                    | Type                              | Null | Key | Default               | Extra |
+--------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host                     | char(255)                         | NO   | PRI |                       |       |
| User                     | char(32)                          | NO   | PRI |                       |       |
```

在mysql中，对应的用户管理中，是由对应的Host和User共同组成主键来区分用户。

User：代表用户的用户名

Host：代表本质是允许访问的客户端（IP或者主机地址）。如果host使用%代表所有的用户（客户端）都可以访问。

## 2、创建用户

1、 直接使用root用户在mysql.user表中插入记录（不推荐）

2、 专门创建用户的SQL指令

基本语法：create user 用户名 identified by ‘明文密码’;

用户：用户名@主机地址

主机地址：’’ / ‘%’

```
mysql> create user 'user1'@'%' identified by '123456';
Query OK, 0 rows affected (0.07 sec)
```

查看mysql.user表中是否存在新增的用户

```
*************************** 2. row ***************************
                    Host: %
                    User: user1
```

简化版创建用户（谁都可以访问，不需要密码）

```
mysql> create user user2;
#不限定客户端IP，没有密码的用户。
```

当用户创建完成之后，用户是否可以使用?

```
C:\mysql\mysql-8.0.22-winx64\bin>mysql -uuser2
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 29
Server version: 8.0.22 MySQL Community Server - GPL

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>
```

## 3、删除用户

注意：mysql中user是带着host本身的（具有唯一性）

基本语法：drop user 用户名@host;

```
mysql> drop user user2;
Query OK, 0 rows affected (0.05 sec)
```

## 4、修改用户密码

Mysql中提供了多种修改的方式：基本上都必须使用对应提供的一个系统函数：password()，需要靠该函数对密码进行加密处理。

1、 使用专门的修改密码的指令

基本语法：set password for 用户 = password(‘新的明文密码’);

2、 使用更新语句update来修改表

基本语法：update mysql.user set password = password(‘新的明文密码’) where user = ‘’ and host= ‘’;

3、mysql 8.0 之后的版本

ALTER USER 'user1'@'%' IDENTIFIED WITH mysql\_native\_password BY 'mysql\@123';

Query OK, 0 rows affected (0.06 sec)

## 5、权限管理

在mysql中将权限管理分为三类：

1、 数据权限：增删改查（select\update\delete\insert）

2、 结构权限：结构操作（create\drop）

3、 管理权限：权限管理（create user\grant\revoke）：通常只给管理员如此权限

### 5.1 授予权限：grant

将权限分配给指定的用户

基本语法：grant 权限列表 on 数据库/*.表名/* to 用户;

权限列表：使用逗号分隔，但是可以使用all privileges代表全部权限

数据库.表名：可以是单表（数据库名字.表名），可以是具体某个数据库（数据库.*），也可以整库（*.\*）

```
mysql> grant select on mydatabase_backup.class to 'user1'@'%';
Query OK, 0 rows affected (0.07 sec)
```

登陆user1用户查看：

```
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydatabase_backup  |
+--------------------+
2 rows in set (0.05 sec)

mysql> use mydatabase_backup;
Database changed
mysql> show tables;
+-----------------------------+
| Tables_in_mydatabase_backup |
+-----------------------------+
| class                       |
+-----------------------------+
1 row in set (0.04 sec)
```

### 5.2 取消权限：revoke

权限回收：将权限从用户手中收回

基本语法：revoke 权限列表/all privileges on 数据库/*.表/* from 用户;

```
mysql> revoke all privileges on mydatabase_backup.class from 'user1'@'%';
Query OK, 0 rows affected (0.04 sec)
```

登陆user1用户查看：

```
mysql> show tables;
+-----------------------------+
| Tables_in_mydatabase_backup |
+-----------------------------+
| class                       |
+-----------------------------+
1 row in set (0.04 sec)

mysql> show tables;
ERROR 1044 (42000): Access denied for user 'user1'@'%' to database 'mydatabase_backup'
mysql>
```

### 5.3 刷新权限：flush

Flush：刷新，将当前对用户的权限操作，进行一个刷新，将操作的具体内容同步到对应的表中。

基本语法：flush privileges;

```
mysql> flush privileges;
Query OK, 0 rows affected (0.05 sec)
mysql>
```

## 6、密码丢失的解决方案

如果忘记了root用户密码，就需要去找回或者重置root用户密码

1、 停止服务

```
net stop mysql
```

2、 重新启动服务：mysqld.exe –skip-grant-tables //启动服务器但是跳过权限

```
mysqld.exe --skip-grant-tables
```

3、 当前启动的服务器没有权限概念：非常危险，任何客户端，不需要任何用户信息都可以直接登录，而且是root权限：新开客户端，使用mysql.exe登录即可

4、 修改root用户的密码：指定 用户名@host

```
update mysql.user set password = password('root') where user='root' and host='localhost';
```

5、赶紧关闭服务器，重启服务。

```
net start mysql
```

第二种：

1.服务端:

```
mysqld --console --skip-grant-tables --shared-memory,
```

2.客户端:

```
mysql -u root -p

  密码置空:update mysql.user set authentication_string='' where user="root";

  刷新:flush privileges;
```

3.客户端:

```
设置密码:ALTER user 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'admin';

加密规则和密码同时改.ALTER user 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'admin'; OK
```

4.查看

```
select host,user,user password,plugin,authentication_string from mysql.user;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://beret81.gitbook.io/study-notes/mysql-shu-ju-ku/yong-hu-quan-xian-guan-li.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
