jsch mysql,使用Java通过SSH连接到MySQL

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值