我想使用Java连接到Amazon EC2服务器上的MySQL数据库。我能够使用Jsch库创建ssh隧道并将端口转发到该服务器,但是连接到DB总是以异常结束
java.io.EOFException:无法读取服务器的响应。预计读取4个字节,在连接意外丢失之前读取0个字节。
我认为我和Hei(SSH tunneling to remote access MySQL database)
的情况相同这是我的代码:
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();
}
}
}
任何人都可以帮忙解决这个问题吗?感谢
答案 0 :(得分:0)
我使用AppFog(在AWS前面)遇到了完全相同的问题。解决此问题的唯一方法是从我的连接字符串中删除以下内容:
"?useUnicode=true&characterEncoding=UTF-8"
当然,您应该确保这不会影响您的应用程序要求。