Home >Database >Mysql Tutorial >How to Securely Connect to a Remote MySQL Database via SSH Tunnel using Java?
Establish a MySQL Connection through SSH with Java: A Comprehensive Guide
Introduction:
Connecting to a remote MySQL database over an SSH tunnel from Java allows you to access databases securely. Let's delve into the steps and provide a concise code example to get you started.
Steps to Connect:
To connect to a remote MySQL database through SSH, follow these steps:
Create an SSH Tunnel:
Run the following command:
ssh -L 1234:localhost:3306 mysql.server.remote
Establish Java JDBC Connection:
Connect to MySQL:
Use JDBC to connect to the database using the syntax:
jdbc:mysql://localhost:1234/[database]
Example Code Snippet:
The following code snippet provides an example of connecting to a remote MySQL database using JSch and Java JDBC:
import java.sql.Connection; import java.sql.DriverManager; public class RemoteMySQLConnection { public static void main(String[] args) throws Exception { // Create SSH session JSch jsch = new JSch(); Session session = jsch.getSession("username", "hostname", 22); // Set SSH and tunnel parameters session.setConfig("StrictHostKeyChecking", "no"); session.setPortForwardingL(1234, "localhost", 3306); // Connect SSH session session.connect(); // Establish JDBC connection String url = "jdbc:mysql://localhost:1234/database_name"; String user = "mysql_user"; String password = "mysql_password"; Connection conn = DriverManager.getConnection(url, user, password); // Execute queries or perform operations on the database // ... // Close SSH session and database connection conn.close(); session.disconnect(); } }
Remember to substitute your actual database credentials and server information in the code snippet.
The above is the detailed content of How to Securely Connect to a Remote MySQL Database via SSH Tunnel using Java?. For more information, please follow other related articles on the PHP Chinese website!