gpt4 book ai didi

java - 通过 ssh (java) 连接到 mysql 数据库

转载 作者:行者123 更新时间:2023-11-28 23:33:06 25 4
gpt4 key购买 nike

我需要通过 ssh 连接连接到 Mysql RDS 数据库,我尝试过打开一个 ssh 隧道然后连接到该数据库,但它没有用。

下面是我的代码:

 int lport = 3306;
String host = "10.254.64.135";
String rhost = "localhost";
int rport = 8000;
String user = "ubuntu";
String dbuserName = "someusername";
String dbpassword = "somepassword";
String dburl = "jdbc:mysql://somedbhost.us-east-1.rds.amazonaws.com:3306";
String driverName = "com.mysql.jdbc.Driver";
String driverName2 = "org.gjt.mm.mysql.Driver";

Session session = null;

try {

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("C:\\Users\\rop\\workspace\\awskey.pem");
session.setConfig(config);
session.connect();
System.out.println("Connected through SSH");
final int assinged_port = session.setPortForwardingL(rport, host,lport );
System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport);
System.out.println("Port Forwarded");

//mysql database connectivity
Class.forName("com.mysql.jdbc.Driver").newInstance();
//String url = "jdbc:mysql://localhost:" + rport + "/" + db;
con = DriverManager.getConnection(dburl, dbuserName, dbpassword);
System.out.println("Mysql Database connection established");
System.out.println("DONE");

以上代码因以下异常而崩溃,并在“con = DriverManager.getConnection(dburl, dbuserName, dbpassword);”这一行崩溃:

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.

意思是当我们从 mysql workbench 连接时它确实连接正常,在快照下面:

enter image description here

请注意,ssh 主机 ip 与 db 主机 ip 不同

谢谢。

最佳答案

您需要将 JDBC url 中的主机名和端口替换为 localhost 以及您转发的本地端口,您称之为 rport:

dburl = "jdbc:mysql://localhost:"+ rport;

另外,我不确定 MySQL JDBC Driver 是否支持在不指定数据库名称的情况下连接到数据库服务器:

dburl = "jdbc:mysql://localhost:"+ rport + "/yourdatabasename";

此外,如果 MySQL 服务器与 SSH 服务器不在同一台机器上运行,请确保您可以从 SSH 服务器连接到数据库服务器。MySQL 默认不允许远程连接。

关于java - 通过 ssh (java) 连接到 mysql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36745762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com