Home > Database > Mysql Tutorial > How to Securely Connect to a Remote MySQL Database from Java using SSH Tunneling?

How to Securely Connect to a Remote MySQL Database from Java using SSH Tunneling?

Mary-Kate Olsen
Release: 2024-11-29 05:11:15
Original
492 people have browsed it

How to Securely Connect to a Remote MySQL Database from Java using SSH Tunneling?

Connecting to Remote MySQL Database over SSH in Java

Problem Statement:

Accessing a MySQL database hosted on a remote server using a secure SSH tunnel from a Java application.

Solution:

To establish an SSH tunnel and connect to a remote MySQL database from Java, you can leverage the JSch library. Here's an overview of how to achieve this:

  1. Create an SSH Tunnel:

Use the JSch Session class to create a tunnel from a local port (e.g., 1234) to the database's port (e.g., 3306) on the remote server.

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

// Establish an SSH session
JSch jsch = new JSch();
Session session = jsch.getSession("username", "remoteServerAddress", 22);

// Set connection parameters
session.setPassword("password");
session.setPortForwardingL(1234, "localhost", 3306);

// Connect to the SSH server
session.connect();
Copy after login
  1. Establish JDBC Connection to MySQL:

With the SSH tunnel active, you can establish a JDBC connection to the MySQL database using the local port you created.

import java.sql.Connection;
import java.sql.DriverManager;

// Establish a JDBC connection
Connection connection = DriverManager.getConnection(
  "jdbc:mysql://localhost:1234/[database]", 
  "username", 
  "password"
);
Copy after login

Example Usage:

// Example usage: retrieve data from the remote database
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM table_name");
Copy after login

The above is the detailed content of How to Securely Connect to a Remote MySQL Database from Java using SSH Tunneling?. 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