Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SSH tunnel and connect to a database using IntelliJ and JDBC?

I'm having issues connecting to a database hosted on a server using IntelliJ and JDBC. With the command line, the command:

ssh username@server -L 11100:ct1:28017 -N

creates a tunnel successfully and the command:

psql db_name -h localhost -p 11100 db_username

connects to the database fine and allows me to use it. How would this be translated correctly into the IntelliJ Data Sources and the SSH tunnel tools?

At the moment, for the SSH tunnel settings I have:

Proxy Host: server

Port: 22

Proxy user: username

For the general tab I have:

host: localhost

port: 28017

database: db_name

user: db_username

The connection returns successfully after testing the connection. Inside my program I have:

Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:28017/db_name", user, password);

The URL parameter is the one generated by IntelliJ. This however gives me an error "Connection to localhost:28017 refused."

Any ideas on what I am doing wrong?

like image 452
echoeida Avatar asked Feb 11 '16 10:02

echoeida


People also ask

Can I use JDBC in IntelliJ?

Configure a JDBC driver from the existing connection ) that is in the lower-right part of the window. ) and select Custom JARs…. In the file browser, navigate to the JAR file of the JDBC driver, select it, and click OK. In the Class field, specify the value that you want to use for the driver .

Can you ssh in IntelliJ?

You can launch an SSH Session right from IntelliJ IDEA. By running commands in a dedicated SSH terminal, you can access data on a remote Web server or a Vagrant instance (virtual machine) via an SSH tunnel, mainly upload and download files.

How does IntelliJ connect to Java project with Database?

To add a new database connection (called a data source in IntelliJ), open the Database window View -> Tool Windows -> Databases, then click the + sign and select Data Source and then MySQL from the sub-menu. The defaults for the MySQL connection should for a local install of MySQL.


2 Answers

Here's my setup via intellij if anyone is looking for simple solution without external libraries.

  1. Open Database view (View -> Tool Windows -> Database).
  2. Add new DataSource (right-click, New -> Data Source -> Postgres/Mysql). In host, use 127.0.0.1 (not localhost, sometimes localhost is not properly resolved).
  3. Fill in rest of the fields as configured on your remote host.

enter image description here

Now click on SSH/SSL tab and configure ssl tunnel:

enter image description here

like image 128
gmode Avatar answered Sep 30 '22 21:09

gmode


Do you connect to SSH server from a java client like SSHJ (https://github.com/hierynomus/sshj) ?

The URL on your DriverManager seems wrong: try port 11100 instead.

like image 30
Xvolks Avatar answered Sep 30 '22 20:09

Xvolks