how to connect to mysql from java

February 9, 2018 470 views
Java MySQL Ubuntu 16.04

Hi,
I need to connect to mySQL from java I don't know what's code I need to write_
it's different between localHost database and ssh database. Can I connect to my database from java application ?

1 Answer

The most secure way to connect to a remote MySQL server is to set up an SSH tunnel. This will use a secure SSH session to bind port 3306 on your Droplet to whatever port you want on your local machine, and forward all traffic through the secure tunnel. This will allow you to connect to MySQL without enabling true remote access, as the traffic is going through the SSH tunnel so MySQL considers it local traffic.

Take a look at this tutorial, specifically Example 1:

You will need to replace port 110 with 3306 but the rest should be the same. Once you have the tunnel set up, you can connect to your database using Java the same way you would if the server were hosted on your local machine. If you already have a MySQL server installed locally, you might want to use a different port than 3306 on the local end.

In this article, you'll learn how to create a safe, encrypted tunnel between your computer and your VPS along with how to bypass limits in a corporate network, how to bypass NAT, etc.
Have another answer? Share your knowledge.