在使用 MySQL 服务器作为数据库的 Java 项目 工作时,我不得不面对这个挑战。
我是这样做的:
首先,确认您的 MySQL 服务器配置允许远程连接。使用您喜欢的文本编辑器打开 MySQL 服务器配置文件:
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
向下滚动到 bind-address 行并确保将其注释掉或替换为0.0.0.0(以允许所有远程连接)或替换为Ip-Addresses 您希望从中进行远程连接。
进行必要的更改后,保存并退出配置文件。通过重新启动 MySQL 服务来应用对 MySQL 配置文件所做的更改:
sudo systemctl restart mysql
接下来,在安装它的服务器上登录 MySQL 服务器控制台:
mysql -u root -p
输入你的mysql用户密码
检查您想要的用户已经有权访问的主机。在我的情况下,用户是root:
SELECT host FROM mysql.user WHERE user = "root";
这给了我这个输出:
+-----------+
| host |
+-----------+
| localhost |
+-----------+
接下来,我运行下面的命令来授予root 用户对名为my_database 的数据库的远程访问权限:
USE my_database;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'my-password';
注意:% 授予用户从网络上所有主机的远程访问权限。您可以使用以下命令指定要授予用户访问权限的各个主机的 IP 地址 - GRANT ALL PRIVILEGES ON *.* TO 'root'@'Ip-Address' IDENTIFIED BY 'my-password';
之后,我检查了用户现在可以访问的 主机。在我的情况下,用户是root:
SELECT host FROM mysql.user WHERE user = "root";
这给了我这个输出:
+-----------+
| host |
+-----------+
| % |
| localhost |
+-----------+
最后,您可以尝试使用以下命令从另一台服务器连接到 MySQL 服务器:
mysql -u username -h mysql-server-ip-address -p
其中u代表用户,h代表mysql-server-ip-address和p 代表密码。所以在我的情况下是:
mysql -u root -h 34.69.261.158 -p
输入你的mysql用户密码
您应该根据您的 MySQL 服务器版本获得此输出:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.31 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>
资源:How to Allow Remote Connections to MySQL
就是这样。
我希望这会有所帮助