JDBC Basics |
Suppose that the owner of The Coffee Break wants to display his current coffee prices in an applet on his web page. He can be sure of always displaying the most current price by having the applet get the price directly from his database.
In order to do this, he needs to create two files of code, one with applet code, and one with HTML code. The applet code contains the JDBC code that would appear in a regular application plus additional code for running the applet and displaying the results of the database query. In our example, the applet code is in the file
OutputApplet.java
. To display our applet in an HTML page, the fileOutputApplet.html
tells the browser what to display and where to display it.The rest of this section will tell you about various elements found in applet code that are not present in standalone application code. Some of these elements involve advanced aspects of the Java programming language. We will give you some rationale and some basic explanation, but explaining them fully is beyond the scope of this tutorial. For purposes of this sample applet, you only need to grasp the general idea, so don't worry if you don't understand everything. You can use the applet code as a template, substituting your own queries for the one in the applet.
Writing Applet Code
To begin with, applets will import classes not used by standalone applications. Our applet imports two classes that are special to applets: the class
Applet
, which is part of thejava.applet
package, and the classGraphics
, which is part of thejava.awt
package. This applet also imports the general-purpose classjava.util.Vector
so that we have access to an array-like container whose size can be modified. This code usesVector
objects to store query results so that they can be displayed later.All applets extend the
Applet
class; that is, they are subclasses ofApplet
. Therefore, every applet definition must contain the wordsextends
Applet
, as shown here:public class MyAppletName extends Applet { . . . }In our applet example, this line also includes the words
implements
Runnable
, so it looks like this:public class OutputApplet extends Applet implements Runnable { . . . }
Runnable
is an interface that makes it possible to run more than one thread at a time. A thread is a sequential flow of control, and it is possible for a program to be multithreaded, that is, to have many threads doing different things concurrently. The classOutputApplet
implements the interfaceRunnable
by defining the methodrun
, the only method inRunnable
. In our example therun
method contains the JDBC code for opening a connection, executing a query, and getting the results from the result set. Since database connections can be slow, and can sometimes take several seconds, it is generally a good idea to structure an applet so that it can handle the database work in a separate thread.Similar to a standalone application, which must have a
main
method, an applet must implement at least oneinit
,start
, orpaint
method. Our example applet defines astart
method and apaint
method. Every timestart
is invoked, it creates a new thread (namedworker
) to re-evaluate the database query. Every timepaint
is invoked, it displays either the query results or a string describing the current status of the applet.As stated previously, the
run
method defined inOutputApplet
contains the JDBC code. When the threadworker
invokes the methodstart
, therun
method is called automatically, and it executes the JDBC code in the threadworker
. The code inrun
is very similar to the code you have seen in our other sample code with three exceptions. First, it uses the classVector
to store the results of the query. Second, it does not print out the results but rather adds them to theVector
results
for display later. Third, it likewise does not print out exceptions and instead records error messages for later display.Applets have various ways of drawing, or displaying, their content. This applet, a very simple one that has only text, uses the method
drawString
(part of theGraphics
class) to display its text. The methoddrawString
takes three arguments: (1) the string to be displayed, (2) thex
coordinate, indicating the horizontal starting point for displaying the string, and (3) they
coordinate, indicating the vertical starting point for displaying the string (which is below the text).The method
paint
is what actually displays something on the screen, and inOutputApplet.java
, it is defined to contain calls to the methoddrawString
. The main thingdrawString
displays is the contents of theVector
results
(the stored query results). When there are no query results to display,drawString
will display the current contents of theString
message
. This string will be "Initializing" to begin with. It gets set to "Connecting to database" when the methodstart
is called, and the methodsetError
sets it to an error message when an exception is caught. Thus, if the database connection takes much time, the person viewing this applet will see the message "Connecting to database" because that will be the contents ofmessage
at that time. (The methodpaint
is called by AWT when it wants the applet to display its current state on the screen.)The last two methods defined in the class
OutputApplet,
setError
andsetResults
are private, which means that they can be used only byOutputApplet
. These methods both invoke the methodrepaint
, which clears the screen and callspaint
. So ifsetResults
callsrepaint
, the query results will be displayed, and ifsetError
callsrepaint
, an error message will be displayed.A final point to be made is that all the methods defined in
OutputApplet
exceptrun
aresynchronized
. The keywordsynchronized
indicates that while a method is accessing an object, othersynchronized
methods are blocked from accessing that object. The methodrun
is not declaredsynchronized
so that the applet can still paint itself on the screen while the database connection is in progress. If the database access methods weresynchronized
, they would prevent the applet from being repainted while they are executing, and that could result in delays with no accompanying status message.To summarize, in an applet, it is good programming practice to do some things you would not need to do in a standalone application:
Running an Applet
Before running our sample applet, you need to compile the file
OutputApplet.java
. This creates the fileOutputApplet.class
, which is referenced by the fileOutputApplet.html
.The easiest way to run an applet is to use the appletviewer, which is included as part of the JDK. Simply follow the instructions below for your platform to compile and run
OutputApplet.java
:
- UNIX
javac OutputApplet.java appletviewer OutputApplet.html- Windows 95/NT
javac OutputApplet.java appletviewer OutputApplet.htmlApplets loaded over the network are subject to various security restrictions. Although this can seem bothersome at times, it is absolutely necessary for network security, and security is one of the major advantages of using the Java programming language. An applet cannot make network connections except to the host it came from unless the browser allows it. Whether one is able to treat locally installed applets as "trusted" also depends on the security restrictions imposed by the browser. An applet cannot ordinarily read or write files on the host that is executing it, and it cannot load libraries or define native methods.
Applets can usually make network connections to the host they came from, so they can work very well on intranets.
The JDBC-ODBC Bridge driver is a somewhat special case. It can be used quite successfully for intranet access, but it requires that ODBC, the bridge, the bridge native library, and JDBC be installed on every client. With this configuration, intranet access works from Java applications and from trusted applets. However, since the bridge requires special client configuration, it is not practical to run applets on the Internet with the JDBC-ODBC Bridge driver. Note that this is a limitation of the JDBC-ODBC Bridge, not of JDBC. With a pure Java JDBC driver, you do not need any special configuration to run applets on the Internet.
**link to APP Sample Code 7 is
OutputApplet.java
, and Sample Code 8 isOutputApplet.html
. The sample code in this section is a demonstration JDBC applet. It displays some simple standard output from the tableCOFFEE**
JDBC Basics |