I want that a Java Swing Desktop application to connect to a MySQL database which is running in a Linux Server.
I connect to this database with MySQL Workbench, using a SSH connection, no problem here, but from the code... impossible so far.
I have tried the following:
private static void doSshTunnel( String strSshUser, String strSshPassword, String strSshHost,
int nSshPort, String strRemoteHost, int nLocalPort, int nRemotePort ) throws JSchException {
final JSch jsch = new JSch();
Session session = jsch.getSession( strSshUser, strSshHost, 22 );
session.setPassword( strSshPassword );
final Properties config = new Properties();
config.put( "StrictHostKeyChecking", "no" );
session.setConfig( config );
session.connect();
session.setPortForwardingL(nLocalPort, strRemoteHost, nRemotePort);
}
public static final Connection conexion() throws JSchException, SQLException {
Connection con = null;
try {
String strSshUser = "xxxx"; // SSH loging username
String strSshPassword = "xxx"; // SSH login password
String strSshHost = "12.345.678.901"; // hostname or ip or SSH server
int nSshPort = 22; // remote SSH host port number
String strRemoteHost = "127.0.0.1"; // hostname or ip of your database server
int nLocalPort = 1234; // local port number use to bind SSH tunnel
int nRemotePort = 3306; // remote port number of your database
String strDbUser = "dbuser"; // database loging username
String strDbPassword = "dbpw"; // database login password
doSshTunnel(strSshUser, strSshPassword, strSshHost, nSshPort, strRemoteHost, nLocalPort, nRemotePort);
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:"+nLocalPort+"/dbname", strDbUser, strDbPassword);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (JSchException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
But I get the error:
com.jcraft.jsch.JSchException: PortForwardingL: local port 127.0.0.1:1234 cannot be bound.
...
Caused by: java.net.BindException: Address already in use: JVM_Bind
I've seen this issue in some other posts... trying to change the port 1234 does not work... I've tried with many ports but I always get the same result...