tags:

views:

183

answers:

3

If I run this code: http://www.danny92.pastebin.com/m1f84b972

You will see that my Database connection connects then disconnects after actionPerformed.... why? :(

A: 

Applets have many resctrictions including network restrictions. Don't forget that applets run from the client side and not server side, therefore as a policy, applet was restricted to access company internal networks (the private networks)...

In short, your code is trying to access your database server (as it never connects because of the network restrictions placed on applets). It's trying to call a private network from a client side. Javascript follows the same restriction as it must never access a private network from client side.

More info here (http://www.wutka.com/hackingjava/ch3.htm)

The Elite Gentleman
So what would be the best way to connect a database to java applet?
Dan
1) Create a servlet that you can call from applet using URLConnection. That way, servlet talks directly to the database.2) Create a Web Service or RESTful application that your applet can call from.
The Elite Gentleman
+3  A: 

I wouldn't recommend that an applet connect directly to a database. This exposes the database directly on the network - not a good practice.

A better idea might be to put a servlet in between the applet and the database. This will have several beneficial effects:

  1. Servlet can manage security
  2. Servlet engine can use a connection pool
  3. Servlet can handle several simultaneous connections at once for better scaling
duffymo
2. You could put a transparent pool between the applet and database server. 3. I don't follow. But +1 for not having the applet connect to the database (although it is much easier to write, in some situations).
Tom Hawtin - tackline
"transparent" pool? I'm not familiar with the term. What's managing that if it's not an app server? As for 3, I'm referring to the fact that it'd be easier to scale out horizontally using servlets that connections to a database. Isn't that one of the reasons why client/server was supplanted?
duffymo
Guys.. you're talking to someone who's never worked with JDBC but has with mySQL. Show some links or example? :) Thanks.
Dan
A: 

Line 39 has this code:

  Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jgame", props);

Thus you only assign the Connection to a local variable, not the con member variable in your applet.

Replace it with

  con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jgame", props);
nos