SSH Tunneling with Java for Remote MySQL Database Connectivity
To connect to a remote MySQL database through an SSH tunnel using Java, an effective approach is to leverage the JSch library. This library empowers you to establish SSH2 connections and utilize various features such as port forwarding.
Consider a scenario where you aim to remotely access a MySQL server listening on port 3306. From your local machine, you can establish an SSH tunnel using JSch as follows:
import com.jcraft.jsch.*; public class SSHMySQLTunnel { public static void main(String[] args) throws Exception { // Replace with SSH server hostname String sshHost = "ssh.server.com"; // SSH port number int sshPort = 22; // Replace with SSH username String sshUsername = "username"; // Replace with SSH password String sshPassword = "password"; // Replace with MySQL server hostname String mysqlHost = "mysql.server.com"; // MySQL port number (assuming 3306) int mysqlPort = 3306; // Local port to forward to (1234 in this example) int localPort = 1234; JSch jsch = new JSch(); Session session = jsch.getSession(sshUsername, sshHost, sshPort); session.setPassword(sshPassword); session.connect(); int assingedPort = session.setPortForwardingL(localPort, mysqlHost, mysqlPort); System.out.println("SSH tunnel established. Forwarded port " + localPort + " to " + mysqlHost + ":" + mysqlPort); // Establish JDBC connection to MySQL using the tunnel String jdbcUrl = "jdbc:mysql://localhost:" + localPort + "/[database]"; // ... } }
Once the SSH tunnel is established, you can utilize a JDBC connection to MySQL as usual, using the local port (1234) specified in the SSH tunnel.
The above is the detailed content of How Can I Connect to a Remote MySQL Database via SSH Tunnel Using Java?. For more information, please follow other related articles on the PHP Chinese website!