使用 Java 通过 SSH 连接到远程 MySQL 数据库 [英] Connect to remote MySQL database through SSH using Java

查看:59
本文介绍了使用 Java 通过 SSH 连接到远程 MySQL 数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 Java 应用程序通过 SSH 连接到远程 MySQL 数据库?小代码示例对我很有帮助,我很感激.

How can I connect to remote MySQL database through SSH from java application? Small code example is helpful for me and I'd appreciate this.

推荐答案

我的理解是,您想访问在远程机器上运行的 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 客户端创建从本地机器上的端口 1234 到远程机器上的端口 3306 的隧道,您需要在本地机器上键入以下命令:

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.

这篇关于使用 Java 通过 SSH 连接到远程 MySQL 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆