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
JDBC Connection
Once the SSH tunnel is established, you can use JDBC to connect to the MySQL database:
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(); } }
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!