1

I set up a simple JDBC Connection to connect to my local running MySQL instance. The connection works fine when I set the IP to "localhost" or "127.0.0.1", but fails when I use my public IP address. I'm not sure if it is a configuration issue with Windows 10, MySQL, or something else entirely.

My code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JDBCconnectionTester {

  public static void main(String[] args) {
    System.out.println(queryDB("127.0.0.1", "testdb", "testuser", "testpasswd"));
  }


  /**
   * Connect to MySQL database at given host
   * 
   * @param ip
   * @param database
   * @param username
   * @param password
   * @return
   */
  public static String queryDB(String ip, String database, String username, String password) {
    String data;
    data = "";
    try {
      Class.forName("com.mysql.jdbc.Driver");
      Connection con = DriverManager.getConnection(("jdbc:mysql://" + ip + ":3306/" + database),
          username, password);
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("select * from roles");
      while (rs.next())
        data += rs.getString(1) + "  " + rs.getString(2) + "  " + rs.getString(3) + "\n";
      con.close();
    } catch (Exception e) {
      data = "Error with JDBC Connection: \n\n" + e;
    }
    return data;
  }

}

The error I recieve is:

Error with JDBC Connection: 

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.
Alex Conner
  • 240
  • 5
  • 19
  • Have you already looked into port forwarding on your network? – Joshua Schlichting Mar 02 '17 at 18:41
  • 1
    Default config of MySQL is to only listen on 127.0.0.1, IIRC. Also, what exactly do you mean with "public IP"? – Mark Rotteveel Mar 02 '17 at 18:53
  • @JoshuaSchlichting No I have not I will look into how to do that next. Thanks! – Alex Conner Mar 02 '17 at 19:33
  • @MarkRotteveel Okay, good to know. I will look into where I can change that. By Public IP, I mean simply what results when I google "My Ip address", several sites return the same result. – Alex Conner Mar 02 '17 at 19:35
  • Also, I tried the top suggestion in this [thread](http://stackoverflow.com/questions/14779104/how-to-allow-remote-connection-to-mysql) of making a new user for remote connection, and unfortunately got the same result. – Alex Conner Mar 02 '17 at 19:39

0 Answers0