【问题标题】:Getting "Communications Link Failure" when connecting to MySQL连接到 MySQL 时出现“通信链接失败”
【发布时间】:2025-12-12 04:40:01
【问题描述】:

我正在构建一个需要远程数据库连接的 Java 应用程序。我已经使用 Eclipse 导入了 mysql 的 JDBC 驱动程序,据我所知,所有内容都已正确输入。服务器主机已启用我的IP进行更改,并且用户名和密码已确认。

public class Shop {
Connection connection = null;

String driverName = "com.mysql.jdbc.Driver";
String username = "username";
String password = "password";
String hostURL = "jdbc:mysql://IPAddress:Port/databaseName";


public Shop() {};

public boolean connectDB() {


    try {
        Class.forName(driverName);

        connection =  DriverManager.getConnection(hostURL,username,password);
    } catch (ClassNotFoundException e) {  
        System.out.println("ClassNotFoundException : "+e.getMessage()); 
        return false;
    } catch (SQLException e) {
        System.out.println(e.getErrorCode());
        System.out.println(e.getMessage());
        return false;
    }
    return true;


}
public static void createAndShowGUI() {
    JFrame frame = new JFrame("Store");

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setPreferredSize(new Dimension(800,600));
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

public static void main(String[] args) {
    Shop s = new Shop();
    System.out.println("Connection : " + s.connectDB());

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });




}
}

【问题讨论】:

  • 数据库服务器是远程的吗?可能是防火墙。
  • 是的,它是远程的。我会调查防火墙交易
  • telnet ipaddress port 看看能不能连接

标签: java mysql database jdbc


【解决方案1】:

您是否验证了IPAddressPortdatabaseName?如果是这样,可能有防火墙。您可能可以使用类似的方式设置 ssh 端口转发,

ssh -L LocalPort:IPAddress:RemotePort username@IPAddress

那么您应该可以通过localhost:localport 进行连接。在 Windows 上,您可以以完全相同的方式使用cygwin(如上)或putty(通过简单的 GUI)。我确定还有其他选择(比如 VPN)。

【讨论】:

  • 是的,我已经验证了所有这些。我之前也尝试过直接与腻子连接,但无济于事。 windows上可以直接通过putty传递上面的命令吗?
  • 在腻子中,您必须在连接设置中使用端口转发选项。远程数据库在哪里?联系房东?
  • 使用 cygwin 你可以像上面一样运行它。