I can not connect to the production database using javax.sql.DataSource, error:

java.net.ConnectException: Connection refused: connect mysql

When using mysql workbench connection occurs. There I am using ssh connection. How to make too in?

 public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://255.255.255.255:3306/some_db"); dataSource.setUsername("xxx"); dataSource.setPassword("yyy"); return dataSource; } 

The same configuration works for the local H2 database.

  • one
    Maybe the production base is not accessible from the outside and it is necessary to push the ssh tunnel? - MichaelPak
  • Maybe, and how to throw a ssh tunnel? - cadmy
  • 2
    If the server IP is 255.255.255.255 , and mysql works on port 3306 , then ssh -L 33066:127.0.0.1:3306 user@255.255.255.255 . And connect from java to 127.0.0.1:33066 . - MichaelPak
  • one
    probably, mysql-connector is not able to establish an ssh-tunnel to itself. Google proposes to raise the ssh-tunnel via JSch and then connect to the local address - zRrr
  • one
    if you run on Windows, then the tunnel can be built through the putty program. - MichaelPak

1 answer 1

Probably, access to the database is only local access. In order to connect remotely to the database, you need to push the SSL tunnel to the server. You can do it in two ways:

  1. Throw a tunnel from the terminal:

     ssh -L 33066:127.0.0.1:3306 user@255.255.255.255 

    And in Java, connect as follows:

     dataSource.setUrl("jdbc:mysql://127.0.0.1:33066/some_db"); 
  2. Throw a tunnel out of java. Described in more detail here .