I want to connect to MySQL database on Amazon EC2 server using Java. I am able to create ssh tunnel using Jsch library and forward ports to that server, however connecting to DB always ends with exception
java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
I think i am stuck in the same situation as Hei (SSH tunneling to remote access MySQL database)
Here is my code:
public static void main(final String[] args) throws SQLException {
final int lport = 3306;
final String host = "xxx.xxx.xxx.xxx";
final String rhost = "xxx.xxx.xxx.xxx";
final int rport = 3306;
final String user = "user";
final String dbuserName = "user";
final String dbpassword = "password";
final String dburl = "jdbc:mysql://localhost:" + rport + "/information_schema?useUnicode=true&characterEncoding=UTF-8";
final String driverName = "com.mysql.jdbc.Driver";
Session session = null;
try {
//Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
final java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
final JSch jsch = new JSch();
session = jsch.getSession(user, host, 22);
jsch.addIdentity("path\\to\\pemfile.pem");
session.setConfig(config);
session.connect();
System.out.println("Connected");
final int assinged_port = session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport);
System.out.println("Port Forwarded");
//mysql database connectivity
Class.forName(driverName).newInstance();
dbConn = DriverManager.getConnection(dburl, dbuserName, dbpassword);
System.out.println("Database connection established");
System.out.println("DONE");
} catch (final Exception e) {
e.printStackTrace();
} finally {
if (dbConn != null && !dbConn.isClosed()) {
System.out.println("Closing Database Connection");
dbConn.close();
}
if (session != null && session.isConnected()) {
System.out.println("Closing SSH Connection");
session.disconnect();
}
}
}
Can anyone help to solve this problem? Thanks
解决方案
I've got exactly the same problem using AppFog (in front of AWS). The only way I could workaround this issue was dropping the following from my connection string:
"?useUnicode=true&characterEncoding=UTF-8"
Off course, you should be sure that this will not affect your application requirements.