Writing and running applets with JDBC

Using a database driver in an applet (html file)

Java applets are invoked from an .html file. A typical .html file has an <APPLET > tag which specifies that an applet needs to be invoked. The parameters of this tag include CODE for the applet class, WIDTH and HEIGHT to specify the size of the window, and, optionally, CODEBASE for the path to the directory where the .class file of the applet is located (by default it's the curent directory).

If the applet uses files that are in a .jar file (jar stands for Java archive), you also need to add the ARCHIVE tag for the .jar file. Below is an example of including a databse driver using the ARCHIVE tag:


< html >
<body>
<applet code = "McKoiApplet.class" archive="mckoidb.jar" width = 800 height = 300>
</applet>
</body>
< /html >

Reminder: to compile and run the applet, type:


javac McKoiApplet.java
appletviewer McKoiApplet.html &

The Java code

Below is an example of an applet which runs an SQL query on a database:


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;

public class McKoiApplet extends JApplet implements Runnable {
    JButton button;
    JTextArea text;
    McKoiApplet me;

    public void init() {
	//WindowUtilities.setNativeLookAndFeel();
	Container content = getContentPane();
	content.setBackground(Color.blue);
	content.setLayout(new FlowLayout());

	button = new JButton("Go");
	content.add(button);
	button.addActionListener(new ButtonListener());

	text = new JTextArea(10, 60);
	text.setLineWrap(true);
	content.add(text);
	
	me = this;
    }

    
 
    public void run() {
	
    }

    public void getResults() {
	text.setText("");

	   try {
	       //System.out.println("I am here");
	       Class.forName("com.mckoi.JDBCDriver").newInstance();
           }
           catch (Exception e) {
             System.out.println(
               "Unable to register the JDBC Driver.\n" +
               "Make sure the JDBC driver is in the\n" +
               "classpath.\n");
           }

           // This URL specifies we are connecting with a database server
           // on localhost.
           String url = "jdbc:mckoi://birch/";

           // The username / password to connect under.
           String username = "cs349";
           String password = "cs349";

           // Make a connection with the database.
           Connection con;
           try {
             con = DriverManager.getConnection(url, username, password);
           }
           catch (SQLException e) {
             System.out.println(
               "Unable to make a connection to the database.\n" +
               "The reason: " + e.getMessage());
             return;
           }

           try {
	       
	     Statement stmt = con.createStatement();
           
	     // using executeQuery():
	     ResultSet rs = stmt.executeQuery(
	         "SELECT * FROM Students "); 

	     
	     // moving forward in the result set:
	     while (rs.next()) {
		 int id = rs.getInt("ID");
		 String first = rs.getString("First_Name");
		 String last = rs.getString("Last_Name");
		 String year = rs.getString("Year");
		 float gpa = rs.getFloat("GPA");
		 Date date = rs.getDate("Date_of_birth");
		 text.append(id + "   " + first + "   " + last + "   ");
		 text.append(year + "   " +  gpa + "   " + date + "\n");
	     }

             // Close the connection when finished
             con.close();

           }
           catch (SQLException e) {
             System.out.println(
               "An error occured\n" +
               "The SQLException message is: " + e.getMessage());
             return;
	   }
    }

    class ButtonListener implements ActionListener {
	public void actionPerformed(ActionEvent e) {
	    me.getResults();
	}

    }
}

Things to notice:

  1. The imports include java.awt and javax.swing for using swing GUI, java.awt.event (needs to be included in addition to jawa.awt!) for event handling, and java.sql for the JDBC package.
  2. The applet extends JApplet class (to be able to use swing components)
  3. The JApllet implements runnable interface so that we can later potentially run it as a thread. That's why it must include run() method. Right now the method does nothing, and it is not essential to our example.
  4. Since JApplet itself is a top-level container, it has a contents pane, and we add components (the JButton and the JTextArea) directly to it.
  5. Since the method getResult() belongs to the class McKoiApplet, we use a class variable me to be able to invoke the method on the applet inside the ActionPerformed() method of the ButtonListener.
  6. Method getResults() establishes connection to the database, sends the SQL query, and displays the results in the text area.

Some material on this page has been adopted from a subset of online sources listed here
This page has been created and is maintained by Elena Machkasova
Comments and suggestions are welcome at emachkas@wellesley.edu

Spring Semester 2002