环境
ubuntu20.04;
mysql 8.0.32-0ubuntu0.20.04.2 for linux on x86_64;
mysql 安装
切换root 用户
sudo su
更新源
sudo apt update
sudo apt upgrade
安装服务器客户端
sudo apt install mysql-server mysql-client
进入MySQL并设置密码
mysql
修改root密码并保存
use mysql;
alter user 'root'@'localhost' identified with mysql_native_password by '123456';
flush privileges;
如果失败可以尝试
use mysql;
alter user 'root'@'%' identified with mysql_native_password by '123456';
flush privileges;
输入 quit 退出后尝试
mysql -u root -p
根据提示输入密码
连接MySQL
查询用户和允许访问的host
use mysql;
select user,host from user;
查询结果
+------------------+-----------+
| user | host |
+------------------+-----------+
| debian-sys-maint | localhost |
| mysql.infoschema | localhost |
| mysql.session | localhost |
| mysql.sys | localhost |
| root | localhost |
+------------------+-----------+
root用户的host中仅有localhost可以访问,修改root的host 修改后可以使用该账户远程连接
update user set host = '%' where user = 'root';
或者
RENAME USER 'root'@'localhost' TO 'root'@'%';
都可以修改host
再次查询
+------------------+-----------+
| user | host |
+------------------+-----------+
| root | % |
| debian-sys-maint | localhost |
| mysql.infoschema | localhost |
| mysql.session | localhost |
| mysql.sys | localhost |
+------------------+-----------+
修改后还连接失败 -- 修改配置文件
没有vim 可以使用gedit 或者 cat也行
sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
将文件中的bind_address修改为0.0.0.0
或者注调 (bind_address前面叫#)
如果没有文件读写权限可以修改权限
chmod num /etc/mysql/mysql.conf.d/mysqld.cnf
其中num为权限代号:222(只写)、444(只读)、666(读写)
重启mysql
sudo service mysql restart
再次连接显示成功