[ Team LiB ] Previous Section Next Section

Using JDBC from JavaServer Pages and Servlets

JDBC can be used through any piece of Java code, including JavaServer Pages or servlets. The following JSP is an example of using JDBC to access the People table in the database, PeopleDB.

Listing 18.1 shows a JSP that queries a Person table using JDBC.

Listing 18.1 Source Code for ShowPeople.jsp
<title>JDBC Example for People Table</title>
<%@ page language="java" import="java.sql.*, java.io.*" %>
    Connection con = null;
        con = DriverManager.getConnection("jdbc:db2j:PeopleDB");
        Statement statement = con.createStatement();
        ResultSet rs = statement.executeQuery("SELECT * FROM People");

        <table border="1"><tr><th>Name</th><th>Age</th>
        while ( rs.next() ) {
            out.println("<tr>\n<td>" + rs.getString("name") + "</td>");
            out.println("<td>" + rs.getByte("age") + "</td>"); + "</td>\n</tr>");
    } catch (IOException ioe) {
    } catch (SQLException sqle) {
    } catch (Exception e) {
    } finally {
        try {
            if ( con != null ) {
        } catch (SQLException sqle) {

This simple JSP uses straight JDBC calls to print all the rows in the People table. You will see later in this hour how this lengthy and complicated JDBC code is greatly simplified using the JSTL SQL tag libraries.

Running the Example


To run this example, you need to tell Cloudscape where to find your database. By default, it looks for database in the "current directory," which is Tomcat's bin/ directory.

A recommended practice is to put all of your databases in one directory. For example, you may put all of your databases in c:\Cloudscape_5.1\data.

By defining the property db2j.system.home=c:\Cloudscape_5.1\data, Cloudscape will be able to find your database.

To do this with Tomcat, run the command

SET JAVA_OPTS="db2j.system.home=c:\Cloudscape_5.1\data"

prior to starting Tomcat.

    [ Team LiB ] Previous Section Next Section