MySQL给root开启远程访问权限(MySQL 8)

提示:如果server和MySQL在同一个主机上,那么就不用设置root远程访问权限了,在配置文件里可以用localhost连接数据库就可以,如下所示
1、在连接服务器后,操作MySQL数据库
这里给root设置的密码是123456,我们也可以改成自己的密码

root@vultr:~/mysql8# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.29 MySQL Community Server - GPL

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

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> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select host,user from user where user='root';
+-----------+------+
| host      | user |
+-----------+------+
| localhost | root |
+-----------+------+
1 row in set (0.00 sec)

mysql> update user set host='%' where user='root' and host='localhost';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

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

mysql> select host,user from user where user='root';
+------+------+
| host | user |
+------+------+
| %    | root |
+------+------+
1 row in set (0.00 sec)
mysql> alter user 'root'@'%' identified with mysql_native_password by '123456';
Query OK, 0 rows affected (0.00 sec)

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


	
注意,这里最后一行是把root密码设置为123456,可以把自定义成自己的密码
2、如果是遇到root连不上数据库的问题,可能是加密规则变了,试试如下处理,这里修改加密规则,这里密码用的是123456,可以改成自己的密码

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY '123456' PASSWORD EXPIRE NEVER; 
Query OK, 0 rows affected (0.01 sec)

mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456'; 
Query OK, 0 rows affected (0.01 sec)

mysql> FLUSH PRIVILEGES; 
Query OK, 0 rows affected (0.01 sec)