title: Connection refused: connect, can't connect database mysql
body: <p>I can't connect remote database. When I connect my own database on localhost, it connects. What's wrong?</p>
  
  <pre><code>    Exception in thread "main" java.lang.IllegalStateException: Cannot connect the database!
  
      Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
  
  The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
  
  Caused by: java.net.ConnectException: Connection refused: connect
  </code></pre>
  
  <p>Java Code:</p>
  
  <pre><code>String url = "jdbc:mysql://ipadress:3306/database?autoReconnect=true&amp;useSSL=false";
          String username = "username";
          String password = "password";
          String query = "SELECT * FROM database";
  
          System.out.println("Connecting database...");
            try {
          // The newInstance() call is a work around for some
          // broken Java implementations
  
          Class.forName("com.mysql.jdbc.Driver").newInstance();
      } catch (Exception ex) {
          // handle the error
      }
          try (Connection connection = DriverManager.getConnection(url, username, password)) {
              System.out.println("Database connected!");
              //Uruchamiamy zapytanie do bazy danych
                          Statement stmt = connection.createStatement();
                          ResultSet rs = stmt.executeQuery(query);
  
                          while (rs.next()) {
  
                          }
  
                          connection.close();
          } catch (SQLException e) {
          throw new IllegalStateException("Cannot connect the database!", e);
          }
      }
  </code></pre>
  
  <p>I can login to database on PHPMyAdmin, I have no root account, it's my friend's database. I checked if port 3306 is open here: <a href="http://www.yougetsignal.com/tools/open-ports/" rel="nofollow noreferrer">http://www.yougetsignal.com/tools/open-ports/</a> and it's closed. Where can I open it? In router settings in "port forwarding"? What private IP and type(TCP or UDP) should I set to open this port?</p>