To start, the following exception
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
can have the following causes:
- IP address or hostname in JDBC URL is wrong.
- Hostname in JDBC URL is not recognized by local DNS server.
- Port number is missing or wrong in JDBC URL.
- DB server is down.
- DB server doesn't accept TCP/IP connections.
- DB server has run out of connections.
- Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
Further, do you realize that an Java Applet physically runs at the client machine? I.e. the machine where the webbrowser runs. The client basically downloads the applet from the webserver and it get executed at client (local) machine. The JDBC connection string jdbc:mysql://localhost:3306
would try to connect to a MySQL database running at the very same machine as where the applet runs. You can't reasonably expect that every client on the world will run a MySQL DB, let alone with your database/table.
If all you want is to access the MySQL server hosted at the server machine (there where the webserver runs) and you want to let the applet communicate with it, then you really have to create and run a webservice at the webserver. Since you tagged this question with [PHP]
as well, I guess that you're using PHP at the server side, in that case, just create a PHP script which executes the MySQL action accordingly based on the request parameters or pathinfo and returns the MySQL results as for example a JSON or XML string. In the Applet, you can use the Java SE builtin java.net.URLConnection
or the more convenienced Apache HttpComponents Client to communicate with the webserver. E.g.
URLconnection connection = new URL(getCodeBase(), "script.php?action=getdetails&productid=1").openConnection();
InputStream response = connection.getInputStream();
// ...
In Java, you could process any JSON response using Google Gson any XML response using JAXP.
That said (and unrelated to the current problem), the JDBC driver name you're using is the deprecated org.gjt.mm.mysql.Driver
. I strongly recommend to use the correct driver name which was introduced over a decade ago to replace the old driver name: com.mysql.jdbc.Driver
. Further, the Class#newInstance()
call after Class#forName()
is also not needed. It was to workaround a bug in the old driver. Also see this explanation.