Home > Database > Mysql Tutorial > How to Connect to a Remote MySQL Database via SSH Tunneling in Java?

How to Connect to a Remote MySQL Database via SSH Tunneling in Java?

Patricia Arquette
Release: 2024-11-29 10:28:11
Original
684 people have browsed it

How to Connect to a Remote MySQL Database via SSH Tunneling in Java?

Establish a Remote MySQL Connection via SSH in Java

Establishing a connection to a remote MySQL database through SSH from a Java application can be achieved by leveraging a combination of SSH tunneling and JDBC. Here's how you can do it:

SSH Tunneling

  1. On your local machine, set up an SSH tunnel to forward port 1234 on your machine to port 3306 on the remote MySQL server. To do this using SSH's command-line client, run: ssh -L 1234:localhost:3306 mysql.server.remote
  2. Use Java's JSch library to create an SSH session that forwards port 1234 to the remote server.

JDBC Connection

Once the SSH tunnel is established, you can use JDBC to connect to the MySQL database:

  1. Create a java.sql.Connection object, specifying the JDBC URL as jdbc:mysql://localhost:1234/[database].
  2. Authenticate with your MySQL credentials and proceed with your database operations.

Code Example

Here's a basic code example to demonstrate the connection:

import com.jcraft.jsch.*;
import java.sql.*;

public class ConnectToRemoteMySQLThroughSSH {

   public static void main(String[] args) throws JSchException, SQLException {
      // SSH Session Setup
      JSch jsch = new JSch();
      Session session = jsch.getSession("username", "host", 22);
      session.setConfig("StrictHostKeyChecking", "no");
      session.setPassword("password");
      session.connect();

      // Port Forwarding
      session.setPortForwardingL(1234, "localhost", 3306);

      // JDBC Connection
      Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:1234/[database]", "root", "password");

      // Database Operations...

      connection.close();
      session.disconnect();
   }
}
Copy after login

The above is the detailed content of How to Connect to a Remote MySQL Database via SSH Tunneling in 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