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.