连接被拒绝:连接,无法连接数据库mysql
问题描述:
我无法连接远程数据库。当我在本地主机上连接我自己的数据库时,它会连接。怎么了?连接被拒绝:连接,无法连接数据库mysql
Exception in thread "main" java.lang.IllegalStateException: Cannot connect the database!
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Caused by: java.net.ConnectException: Connection refused: connect
Java代码:
String url = "jdbc:mysql://ipadress:3306/database?autoReconnect=true&useSSL=false";
String username = "username";
String password = "password";
String query = "SELECT * FROM database";
System.out.println("Connecting database...");
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
//Uruchamiamy zapytanie do bazy danych
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
}
connection.close();
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
我可以登录到数据库上的phpMyAdmin,我没有root帐户,这是我朋友的数据库。我检查了端口3306是否打开:http://www.yougetsignal.com/tools/open-ports/,它已关闭。我可以在哪里打开它?在“端口转发”中的路由器设置?我应该设置什么专用IP和类型(TCP或UDP)来打开此端口?
答
(道歉,如果这个答案是不完整的,但就是不适合评论太多)
1)不要忽视例外。这很糟糕:// handle the error
和catch
块中没有其他东西,如果出现错误,您的代码将不报告错误,并且继续执行(它应该退出/ break/return,具体取决于那段代码在哪里)。我觉得检查"SHOW GLOBAL VARIABLES LIKE 'PORT';"
是不够的。询问你的朋友,数据库守护进程实际上是否监听到你可以连接的网络接口上的3306端口。 MySQL可以配置禁用网络(skip-networking
)或启用,但仅适用于本地计算机(bind-address=127.0.0.1
或localhost
- 应该是bind-address=0.0.0.0
或bind-address=hostname
或公共IP地址...)。
要自己检查,如果您在linux上,请尝试使用nc
或telnet
(如果您没有它,请安装nc
):nc remotehost 3306
。如果你得到“拒绝连接”,那么错误肯定不在你的java代码中,而是在服务器设置中。
可能你可以分享你的代码吗? –
正确提到的远程数据库的URL和凭证? –
是的,他们是 我改变了他们,因为我不想分享我的数据库地址 – Jkrr