Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


how do i run sql statements on a db2/400 database form my java applet

Posted on 2003-10-29
Medium Priority
Last Modified: 2010-05-18
ok i am simply trying to connect to my database so i can run some simple SQL statements

this is proving to be very difficuly for me... i am really new too java in general and am not having much luck

so i guess im asking if anyone has an example of a SIMPLE java applet that will allow me to run some SQL statments

i have the database configured on ODBC, i dont know if that is necessary or not..

but any help would be awsome!
Question by:SOBKing
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
LVL 14

Accepted Solution

sudhakar_koundinya earned 1000 total points
ID: 9647787

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

Author Comment

ID: 9647935
where would i get ibm.netsql

i have seen this line in a few examples i have been looking at
import ibm.netsql.*;
but i dont seem to have that
LVL 14

Expert Comment

ID: 9648059
Install DB2 (server or client) on your machine as your Web server. The Java applet and JDBC support is installed as part of DB2.

Extract DB2's tempjava.sql and ibm.netsql packages from the sqllib\java\ file and move them to the appropriate directories
LVL 14

Expert Comment

ID: 11424049

Featured Post

Enroll in September's Course of the Month

This month’s featured course covers 16 hours of training in installation, management, and deployment of VMware vSphere virtualization environments. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Suggested Courses

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question