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:
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();
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" );
Example Usage:
// Example usage: retrieve data from the remote database Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM table_name");
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!