通过远程服务器连接亚马逊 mysql 和 JDBC

connect amazon mysql with JDBC through remote server

我这里遇到了问题,是否可以JDBC远程连接到亚马逊MySQL服务器?我在 Internet 上搜索解决方案,但最终收到错误

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.

我正在使用 jsch.jar 连接远程服务器,然后调用 JDBC 连接器尝试连接 MySQL 数据库,我已成功连接到远程服务器但我无法连接MySQL 亚马逊数据库,这是我的代码

testPutty t = new testPutty();
        t.connect("admin", "", "xx:xx:xx:xx", "openSSHPrivateKey", 22);
        t.connect();
        System.out.println("connected");
        Class.forName("com.mysql.jdbc.Driver");
        DriverManager.getConnection("jdbc:mysql://staging.ppyhcsxnlkji.ap-southwest-1.rds.amazonaws.com:3306/staging","superuser","password");
        System.out.println("hello world");
        t.close();

首先使用 SSH 设置隧道。您还没有显示 testPutty 是什么,所以我假设它是围绕 Putty 的命令行调用的薄 Java 包装器。设置隧道的命令行选项是

-L[localport]:[host]:[remoteport]

对于您的示例,这将是

-L3306:staging.ppyhcsxnlkji.ap-southwest-1.rds.amazonaws.com:3306

这将设置一个隧道,将本地端口 3306 的连接转发到给定主机 (staging...amazonaws.com) 上的端口 3306,端口 3306 路由通过作为 SSH 命令目标的主机(在您的示例 xx:xx:xx:xx).

然后,您的连接字符串需要使用 localhost 而不是实际的远程:

jdbc:mysql://localhost:3306/staging

如果您的本地主机上的 3306 不可用,因为您也是 运行 MySQL 的本地副本,只需选择一个不同的未使用端口。