[ 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
<html>
<head>
<title>JDBC Example for People Table</title>
</head>
<body>
<%@ page language="java" import="java.sql.*, java.io.*" %>
<%
    Connection con = null;
    try
        Class.forName("com.ibm.db2j.jdbc.DB2jDriver");{
        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>");
        }
        rs.close();
    } catch (IOException ioe) {
        out.println(ioe.getMessage());
    } catch (SQLException sqle) {
        out.println(sqle.getMessage());
    } catch (Exception e) {
        out.println(e.getMessage());
    } finally {
        try {
            if ( con != null ) {
                con.close();
            }
        } catch (SQLException sqle) {
            out.println(sqle.getMessage());
        }
    }
%>
</tr>
</table>
</body>
</html>

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

graphics/watchout_icon.gif

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