I am trying to connect to a remote server using JSch
, the connection seems to be working, it is just that mysql is throwing an error when it is trying to connect:
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.
I have checked the connection string, and it seems to be correct, but why isn't mysql connecting? It connects fine to other database that use a username/password but when I add the SSH tunnel it throws the above error.
Here is the Forward:
lport: 3308, rhost: 127.0.0.1, rport: 3306
Here is the output of my connection string:
jdbc:mysql://127.0.0.1:3308/?zeroDateTimeBehavior=convertToNull
Here is how I am connecting:
// 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);
Here is how I am connection to 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);
}
}