我正在尝试使用JSch
连接到远程服务器,连接似乎正在工作,只是mysql在尝试连接时抛出错误:
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.
我检查了连接字符串,它似乎是正确的,但为什么mysql连接不正确?它可以很好地连接到使用用户名/密码的其他数据库,但是当我添加SSH隧道时,它会抛出上述错误。
这是前锋:
lport: 3308, rhost: 127.0.0.1, rport: 3306
以下是我的连接字符串的输出:
jdbc:mysql://127.0.0.1:3308/?zeroDateTimeBehavior=convertToNull
以下是我的联系方式:
// MySQL Connection Strings
ResultSet info = sql.getConnectionInfo(connectionName);
String host = info.getString("host");
String user = info.getString("user");
String pass = info.getString("pass");
String port = info.getString("port");
// SSH Connection String
ResultSet sshInfo = sql.getSSHSettings(connectionName);
if(sshInfo.next()){
String sshHost = sshInfo.getString("sshHost");
String sshPort = sshInfo.getString("sshPort");
String sshLPort = sshInfo.getString("sshLPort");
String sshUser = sshInfo.getString("sshUser");
String sshPass = sshInfo.getString("sshPass");
String sshPPK = sshInfo.getString("sshPrivateKey");
JSch ssh = new JSch();
try{
if(!sshPPK.equals("")){
ssh.addIdentity(sshPPK);
}
Session session = ssh.getSession(sshUser, sshHost, Integer.parseInt(sshPort));
session.setPassword(sshPass);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
session.setTimeout(4);
String rhost = "127.0.0.1";
int assignedPort = session.setPortForwardingL(Integer.parseInt(sshLPort), rhost, Integer.parseInt(port));
System.out.println(rhost + ":" + assignedPort + " -> " + sshHost + ":" + port);
// Set MySQL port to the tunnel port and the host to localhost
host = rhost;
port = String.valueOf(assignedPort);
}catch(JSchException ex){
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}
}
MysqlWrapper mysqlConn = new MysqlWrapper(host, user, pass, port);
以下是我与MySQL的连接方式:
public void connect(){
try{
if(conn != null){
return;
}
System.out.println(url);
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
}catch(SQLException | ClassNotFoundException ex){
Logger.getLogger(Mysql.class.getName()).log(Level.SEVERE, null, ex);
}
}