Question

how to connect to mysql from java

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 ?


Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

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.