# 更改root密码

mysql 安装之后默认可以直接使用root用户登陆

```bash
# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 11
Server version: 10.2.6-MariaDB-log MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>
```

但这很不安全，所以需要设置登陆密码。

## mysql授权

```sql
 > grant all on *.* to 'root'@'localhost' identified by '123456';
 > flush privileges;
```

命令解析：

* all  ： 所有权限，还可以为mysql命令
* on \*.\*  ：所有库下的所有表
* to ‘root’@‘localhost’  ：给定的用户及主机 ，% 为所有人
* identified by ‘123456’   ：授权密码
* flush privileges;   ：授权后刷新权限

## root修改密码

但是如果忘记了登陆密码呢，需要以下的操作，

编辑配置文件

```bash
vim /etc/my.cnf
# 在[mysqld]中加入 

#不授权
skip-grant
```

保存退出 ，重启mysqld

```bash
service mysqld restart
```

启动mysql 修改密码

```bash
# mysql

> use mysql; # 进入mysql库

> update user set password=password("123456") where user='root'; # 修改root用户密码

> exit; # 退出登陆
```

重新编辑配置文件 ，删除添加的skip-grant

```
vim /etc/my.cnf
```

```bash
# 在[mysqld]中加入 

# 免密码登陆
# skip-grant
```

保存退出 ，重启服务。
