Home > Database > Mysql Tutorial > How Can I Connect to a Remote MySQL Database via SSH Tunnel Using Java?

How Can I Connect to a Remote MySQL Database via SSH Tunnel Using Java?

Patricia Arquette
Release: 2024-12-01 20:00:13
Original
359 people have browsed it

How Can I Connect to a Remote MySQL Database via SSH Tunnel Using Java?

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]";

        // ...
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template