Java Reference
In-Depth Information
Example 18−3: Query.java (continued)
// display the query text as a page heading
out.println("<h1>" + query + "</h1>");
// Now try to execute the query and display the results in a table
Statement statement = null; // An object to execute the query
try {
// Create a statement to use
statement = db.createStatement();
// Use it to execute the specified query, and get result set
ResultSet results = statement.executeQuery(query);
// Ask for extra information about the results
ResultSetMetaData metadata = results.getMetaData();
// How many columns are there in the results?
int numcols = metadata.getColumnCount();
// Begin a table, and output a header row of column names
out.println("<table border=2><tr>");
for(int i = 0; i < numcols; i++)
out.print("<th>" + metadata.getColumnLabel(i+1) + "</th>");
out.println("</tr>");
// Now loop through the "rows" of the result set
while(results.next()) {
// For each row, display the the values for each column
out.print("<tr>");
for(int i = 0; i < numcols; i++)
out.print("<td>" + results.getObject(i+1) + "</td>");
out.println("</tr>");
}
out.println("</table>"); // end the table
}
catch (SQLException e) {
// If anything goes wrong (usually a SQL error) display the
// error to the user so they can correct it.
out.println("SQL Error: " + e.getMessage());
}
finally { // Whatever happens, always close the Statement object
try { statement.close(); }
catch(Exception e) {}
}
}
// Now, display the number of hits on this page by invoking the
// Counter servlet and including its output in this page.
// This is done with a RequestDispatcher object.
RequestDispatcher dispatcher =
request.getRequestDispatcher("/servlet/counter");
if (dispatcher != null) {
out.println("<br>Page hits:");
// Add a request attribute that tells the servlet what to count.
// Use the attribute name defined by the Counter servlet, and
// use the name of this class as a unique counter name.
request.setAttribute(Counter.ATTRIBUTE_NAME,Query.class.getName());
// Tell the dispatcher to invoke its servlet and include the output
dispatcher.include(request, response);
}
Search WWH ::




Custom Search