且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用java通过ssh连接到远程mysql数据库

更新时间:2022-11-30 07:58:11

我的理解是你要访问一个mysql服务器在远程机器上运行并通过SSH隧道监听端口3306。

My understanding is that you want to access a mysql server running on a remote machine and listening on let's say port 3306 through a SSH tunnel.

要使用命令行ssh client从本地计算机上的端口1234到远程计算机上的端口3306创建此类隧道,您可以从本地键入以下命令machine:

To create such a tunnel from port 1234 on your local machine to port 3306 on a remote machine using the command line ssh client, you would type the following command from your local machine:

ssh -L 1234:localhost:3306 mysql.server.remote

要从Java做同样的事情,你可以使用 JSch ,SSH2的Java实现。从其网站:

To do the same thing from Java, you could use JSch, a Java implementation of SSH2. From its website:


JSch允许您连接到sshd服务器并使用端口转发,X11转发,文件传输等,以及您可以将其功能集成到您自己的Java程序中。 JSch根据BSD风格许可证授权。

JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is licensed under BSD style license.

举个例子,看看 PortForwardingL.java 。连接会话后,使用 jdbc:mysql:// localhost:1234 / [database] 等连接URL创建与MySQL的JDBC连接。

For an example, have a look at PortForwardingL.java. Once the session connected, create your JDBC connection to MySQL using something like jdbc:mysql://localhost:1234/[database] as connection URL.