Brought to you by EarthWeb
ITKnowledge Logo Login Graphic Click Here!
Click Here!
ITKnowledge
Search this book:
 
Search the site:
 
EXPERT SEARCH ----- nav

EarthWeb Direct

EarthWeb Direct

EarthWeb sites: other sites

Previous Table of Contents Next


It is remarkably simple to provide the 100-percent Java JDBC driver classes to the calling browser: the classes — the JDBC driver package — must be available in the directory where the applet resides. As soon as the Java applet is loaded in the virtual machine running in the WWW browser, the class loader notices that it needs additional classes, and a call to Class.forName() dynamically loads the appropriate driver class. The Hypertext Transport Protocol (HTTP) server then sends the requested classes.

Snapshot of the Applet

As shown in Figure 10-2, the applet lets you enter a SQL query in a floating window.


Figure 10-2:  The ISQL applet.

Clicking the “Go!” button sends the query to the database and retrieves the results. Figure 10-3 shows the resulting rows of data displayed in another floating window.


Figure 10-3:  Executing SQL statements.

The graphical user interface (GUI) part of this applet was done using Marimba Bongo, which generates a 100 percent portable .gui file containing the persistified GUI objects. This file contains a persistent form of the widgets used in this example. The .gui file is editable using Marimba Bongo, a demo version of which is on the CD-ROM accompanying this book. The unzipped Marimba classes must be in the CLASSPATH or available in the applet’s home directory on the WWW server to run this example.

The HTML File

The following is the HTML file that calls the applet. The connection parameters are passed as arguments to the applet for greater convenience. These parameters specify which JDBC driver to load and which database URL to use.

<applet
name="jsql"
code="jsql.class"
width="430"
height="390"
align="Top"
alt="If you had a java-enabled browser, you would see an applet here."
>
<param name="driver" value="com.sybase.jdbc.SybDriver">
<param name="url" value="jdbc:sybase:Tds:database.eng:8192">
<param name="login" value="guest">
<param name="password" value="javabank">
<param name="catalog" value="javabank">
<hr>If your browser recognized the applet tag,
you would see an applet here.<hr>
</applet>

Source

Listing 10-3 contains the source code for the ISQL applet example. Remember that the Marimba classes must be in the CLASSPATH or in the applet’s home directory on the WWW server to run.

Listing 10-3: An Interactive SQL Applet.

import java.awt.*;
import java.sql.*;
import java.lang.*;
import java.util.*;
import java.net.*;
import marimba.gui.*;
public class jsql extends java.applet.Applet {
Presentation presentation;
PlayerPanel player;
PlayerUtil util;
Connection conn = null;
DatabaseMetaData mtdt = null;
ResultSet rs = null;
/**
* initialize the applet
*/
public void init() {
try {
       presentation = Presentation.getPresentation(new URL(getDocumentBase(),
               "jsql.gui"));
}
catch (MalformedURLException ex) {
       ex.printStackTrace();
}
// create a player panel
setLayout(new BorderLayout());
add("Center", player = new PlayerPanel());
// set the presentation
player.setPresentation(presentation);
// create a player utility object
util = new PlayerUtil(player);
// load applet parameters
((ChoiceWidget) util.getWidget("dataURL")).addChoice(getParameter("url"));
((ChoiceWidget)   util.getWidget("dataDriver")).addChoice(getParameter("driver"));
  util.setText("dataLogin", getParameter("login"));
  util.setText("dataPasswd", getParameter("password"));
  util.setText("dataCatalog", getParameter("catalog"));
  // add some jdbc connection choices
  // jdbc-odbc bridge
  addDriverInfo("jdbc:odbc:data-source-name",
    "sun.jdbc.odbc.JdbcOdbcDriver");
  // sybase's driver
  addDriverInfo("jdbc:sybase:Tds:host.domain.com:8192",
    "com.sybase.jdbc.SybDriver");
  // connect software's sybase driver
  addDriverInfo("jdbc:sybase://host.domain.com:8192",
    "connect.sybase.SybaseDriver");
  // funny driver
  addDriverInfo("foo:bar:database", "foo.bar.Driver");
}
/**
* add a new entry in the url and driver listboxes
*/
public void addDriverInfo(String url, String driver)
{
// add entry for this driver provider
((ChoiceWidget) util.getWidget("dataURL")).addChoice(url);
((ChoiceWidget) util.getWidget("dataDriver")).addChoice(driver);
}
/**
* we handle all gui events here
*/
public boolean handleEvent(Event evt)
{
try {
  if ((evt.id == Event.ACTION_EVENT) && (evt.target instanceof Widget)) {
   Widget w = (Widget)evt.target;
   String nm = w.getName();
   if (nm != null) System.out.println("Event: " + nm);
   // The user has logged in.
   if (nm.equals("dataLoginButton")) {
       String url = util.getText("dataURL").trim();
       String uid = util.getText("dataLogin").trim();
       String pwd = util.getText("dataPasswd").trim();
       String catalog = util.getText("dataCatalog").trim();
       String driver = util.getText("dataDriver").trim();
       try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, uid, pwd);
            if (conn != null) {
                 mtdt = conn.getMetaData();
                 conn.setCatalog(catalog);
            }
       }
       catch (SQLException ex) {
                 System.out.println(ex);
       }
       catch (java.lang.Exception ex) {
                 System.out.println(ex);
            }
        }
   // The user has clicked logout
   if (nm.equals("dataLogoutButton")) {
       if (conn != null) {
                 conn.close();
       }
   }
   // execute the sql query
   if (nm.equals("isqlGoButton")) {
       String query = util.getText("isqlQueryText");
       if (true)
       {
            TableWidget tbl = (TableWidget)
            util.getWidget("isqlResultTable");
            tbl.removeAllRows();
            tbl.removeAllColumns();
            util.show("isqlResultWindow", true);
            ResultSet rs = getSingleRS(query);
            Vector headers = getRSColumnHeadersAsVector(rs);
            int i;
            for (i=0; i<headers.size(); i++)
  //                              tbl.addColumn((String)
                   headers.elementAt(i), ((String) headers.elementAt(i)).length());
                 tbl.addColumn((String) headers.elementAt(i));
            Vector rows = getRSRowsAsVector(rs);
            for (i=0; i<rows.size(); i++)
                 tbl.addRow((Vector) rows.elementAt(i));
            rs.close();
       }
  }
  // close the isql result window
  if (nm.equals("resultCloseButton")) {
       util.show("isqlResultWindow", false);
  }
  }
}
catch(java.lang.Exception ex) {
  ex.printStackTrace();
}
return super.handleEvent(evt);
}
/**
* return the resultset of a simple query
*/
public ResultSet getSingleRS(String sqlText)
{
  ResultSet rs = null;
  int res;
  try {
       Statement st = conn.createStatement();
       if (st.execute(sqlText)) {
            // okay it's not an update count
            rs = st.getResultSet();
       }
       else if ((res = st.getUpdateCount()) != -1) {
            // it's an update count
            // we could could display it
       }
  } catch (SQLException ex) { ex.printStackTrace(); }
  return rs;
}
/**
* return the column headers of a resultset as vector
*/
public Vector getRSColumnHeadersAsVector(ResultSet rs) {
  int i;
  Vector v = new Vector();
  try {
       ResultSetMetaData rsmd = rs.getMetaData();
       int numCols = rsmd.getColumnCount();
       // fetch column headers
       for (i = 1; i <= numCols; i++)
       {
            v.addElement(rsmd.getColumnLabel(i));
       }
  }
  catch (SQLException ex)
  {
  }
  return v;
}
/**
* return a resultset as vector
*/
public Vector getRSRowsAsVector(ResultSet rs) {
ProgressIndicatorWidget bar = (ProgressIndicatorWidget)   util.getWidget("sqlProgressBar");
  int barValue = 0;
  Vector v = new Vector();
  Vector r = null;
  int i;
  try {
       ResultSetMetaData rsmd = rs.getMetaData();
       int numCols = rsmd.getColumnCount();
       bar.setValue(0);
       // step through the rows
       while (rs.next())
       {
            // process the columns
            r = new Vector();
            for (i = 1; i <= numCols; i++)
            {
                 r.addElement(rs.getString(i));
            }
            v.addElement(r);
            if (barValue < 100) {
                 barValue = barValue + 10;
            }
            else {
                 barValue = 0;
            }
            bar.setValue(barValue);
            bar.repaint();
       }
  }
  catch (SQLException ex)
  {
  }
  return v;
}
}


Previous Table of Contents Next
HomeAbout UsSearchSubscribeAdvertising InfoContact UsFAQs
Use of this site is subject to certain Terms & Conditions.
Copyright (c) 1996-1999 EarthWeb Inc. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.