Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to remote MySQL database through SSH using Java

How can I connect to remote MySQL database through SSH from java application? Small code example is helpful for me and I'd appreciate this.

like image 565
Alex Avatar asked Dec 28 '09 06:12

Alex


People also ask

How do I connect to a remote MySQL server using SSH?

Open a new terminal window. Direct your local MySQL client to 127.0. 0.1:3306 with the MySQL server username and password. Your connection to the remote MySQL server will be encrypted through SSH, allowing you to access your databases without running MySQL on a public IP.

Can we connect MySQL with Java?

In Java, we can connect to our database(MySQL) with JDBC(Java Database Connectivity) through the Java code. JDBC is one of the standard APIs for database connectivity, using it we can easily run our query, statement, and also fetch data from the database.


1 Answers

My understanding is that you want to access a mysql server running on a remote machine and listening on let's say port 3306 through a SSH tunnel.

To create such a tunnel from port 1234 on your local machine to port 3306 on a remote machine using the command line ssh client, you would type the following command from your local machine:

ssh -L 1234:localhost:3306 mysql.server.remote 

To do the same thing from Java, you could use JSch, a Java implementation of SSH2. From its website:

JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is licensed under BSD style license.

For an example, have a look at PortForwardingL.java. Once the session connected, create your JDBC connection to MySQL using something like jdbc:mysql://localhost:1234/[database] as connection URL.

like image 171
Pascal Thivent Avatar answered Sep 24 '22 07:09

Pascal Thivent