Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
474
Chapter 18 JDBC and Database Connection Pooling
4.
printTableData
Given a
DBResults
object from a previous query, this method
prints it on the standard output. This is the underlying method
used by
printTable
, but it is also useful for debugging arbi
trary database results.
Listing 18.6 gives the main code, and Listing 18.7 presents the auxiliary
DBResults
class that stores the accumulated results and returns them as
arrays of strings (
getRow
) or wrapped up inside an HTML table (
toHTML
Table
). For example, the following two statements perform a database query,
retrieve the results, and format them inside an HTML table that uses the col
umn names as headings with a cyan background color.
DBResults results =
DatabaseUtilities.getQueryResults(driver, url,
username, password,
query, true);
out.println(results.toHTMLTable("CYAN"));
Since an HTML table can do double duty as an Excel spreadsheet (see
Section 11.2), the
toHTMLTable
method provides an extremely simple
method for building tables or spreadsheets from database results.
Remember that the source code for
DatabaseUtilities
and
DBResults
,
like all the source code in the book, can be downloaded from
www.core
servlets.com
and used or adapted without restriction.
Listing 18.6 DatabaseUtilities.java
package coreservlets;
import java.sql.*;
public class DatabaseUtilities {
/** Connect to database, execute specified query,
* and accumulate results into DBRresults object.
* If the database connection is left open (use the
* close argument to specify), you can retrieve the
* connection with DBResults.getConnection.
*/
public static DBResults getQueryResults(String driver,
String url,
String username,
String password,
String query,
boolean close) {
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved