Java Database Applet
[Geek Home] [PC Hints & Tips] [Internet] [Programming] [Nanet Sites]

The following source code shows you how to connect a DB2 database to a Java Applet. This is a simple example which allows the user to type in an SQL on the tables in a Database and return the results to a scrollable text region. It can easily be altered to work with any kind of database.

Here is an example of how you would call the applet in your HTML file:

<TITLE>Database Example</TITLE>
<H1>Database Example</H1>
<applet code=dbf.class width=650 height=350>

Notice the “applet code” command in the above example. This is where you call your applet class and set the width and height of the applet. The class name is case sensitive.

Below is the source code for the applet. Notice the comments in the java source code. There are sometimes lines of code which are commented out and say that that is the code for the application version. DB2 requires different commands if you’re creating an applet, than if you’re creating an application. Note the differences. If you are using a different database language, this limitation should not apply.

// use net.URL class for database identifier
import java.awt.*;
import java.applet.Applet;

//import java.sql.*;
// application version
// for applet, must use tempjava.sql to work with db2
import tempjava.sql.*;

// load the driver classes
// IBM JDBC drivers to access DB2 database.
// load this package to load the JDBC kernel -- DriverManager.
//import ibm.sql.*;
// application version
// use the applet version
import ibm.netsql.*;

// begin the applet ********************************************

public class dbf extends java.applet.Applet

// constructor for the base applet.
// save in a file called: "" -- case sensitive.
// The applet name must match the file name the applet is stored in.

Button DBFConnect = new Button("Connect to DB2");
TextField QueryField = new TextField(40);
TextArea OutputField = new TextArea(10,95);

// Here we create the objects we plan to use in the applet.
// The Connection object is part of the JDBC API, and is the
// how we link the JdBC’s function to the applet and
// register the driver with DriverManager

Connection con ;

          // Class.forName("ibm.sql.DB2Driver");
          // application call: change to applet call
     }catch(ClassNotFoundException e)
     { e.printStackTrace(); }
} // end static

// since this data is published on the internet, you will need
// to setup a user which can be used anonymously by anyone who
// accesses this data. You can have that user setup with read
// only privileges as well.
// optionally, you can provide url, name, and password fields
// which the user must fill in before being granted access. You
// would not normally want to do this on an open web site.. ie:
// you are granting users the ability to look at a table full of
// products, real estate, etc.
// if this is used on an intranet, you might then want to setup
// name and password fields, but not necessarily the URL.

String url = "jdbc:db2://your.server.url:7777/sample" ;
String Name = "theusername" ;
String Password = "thepassword" ;

public void init()

// create a new instance of GridBagLayout
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints Con = new GridBagConstraints();

// Set the layout of the applet to the gridbag that we created

// Set the font and color of the applet.
setFont(new Font("Ariel", Font.PLAIN, 12));

Con.anchor = GridBagConstraints.CENTER;
Con.fill = GridBagConstraints.NONE;
Con.gridwidth = GridBagConstraints.REMAINDER;

// put the connect button on a row by itself, set the constraints
// and add it.
gridbag.setConstraints(DBFConnect, Con);
add(new Label("SQL Query"));
gridbag.setConstraints(QueryField, Con);

// Add a label and set the colors.
Label result_label = new Label("Result");
result_label.setFont(new Font("Ariel", Font.PLAIN, 16));
gridbag.setConstraints(result_label, Con);

// to make the outputfield take up as much of the remaining
// space as possible, use the weighty=1 to set it apart
// from the previously added components and give it a lot of
// room

gridbag.setConstraints(OutputField, Con);

// show is a deprecated line (used in older java version)
// to use the new 1.1.1 command issue this instead:
// setVisible(true);


} // init


public boolean handleEvent(Event evt)

// The standard format for this method includes the Event class
// where all the properties are set. This is deprecated and
// there is a better way of doing it now, but if you want to
// support the older Java versions, this will work on those and
// 1.1.1 as well.

if ( == QueryField) // if the cursor is in the QueryField
  char c = (char) evt.key ; // check if the Enter key is pressed
  if (c == '\n')
   // pass the contents of the queryfield to the select method
   // the results will show in the outputfield:
   return true ;
  else{ return false ; }

if ( == DBFConnect)
// when the user clicks the “connect” button, connect to the database
// specified in the url and the user name specified in the name
// field.


  // Connect to the database.
  con = DriverManager.getConnection(url, Name, Password);

  // change the name of the button, to indicate the connection
  // has been made
  DBFConnect.setLabel("Reconnect to DB2");

// set exceptions
// an exception will be thrown if there is a problem connecting
// using the specified parameters. The exception will be printed
// to the outputfield and the console.
catch( Exception e)
return true ;
return false ;

}// handleEvent() end

public String Select(String QueryLine)

// Use this method to create the SQL query command
// we return a String

String Output="";
int columns ;
int pos ;


// this can throw exceptions if an invalid query is entered
// or if the connection breaks

// create a Statement class to execute the query.
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(QueryLine);

// use the getMetaData method to return the number of columns
// in the result as an integer variable.


// use the next method to return fetch each row, one at a time.
// this is one method of doing this, using inputStream is another.


  // get each column one by one for each row
  for( pos=1; pos<=columns; pos++)
    // get each field and add a space to it, then append it
    // to the output variable

    Output+=rs.getObject(pos)+" " ;
  } // end for loop

// add a RETURN for each row to start a new line

} // end while loop

// close the query connection streams, but stay connected to the
// database

// catch any exceptions thrown during query or retrieval

catch( Exception e)



// return the result
return Output;


public void destroy()

try {con.close(); }
catch( Exception e)

} // end destroy

}// end applet dbf

 Source  Java Code  C CGI  JavaScript  Java DBF  VAJava & DB2
[Geek Home] [PC Hints & Tips] [Internet] [Programming] [Nanet Sites]

Modified: 02/11/99