response.setContentType("text/html"); // We're outputting HTML PrintWriter out = response.getWriter(); // Where to output it to

// Output document header and a form for entering SQL queries // When the form is submitted, this servlet is reloaded out.println("DB Query\n" + "<body bgcolor=white><h1>DB Query</h1>\n" + "Query: " + "<input type=submit>");

// See if a query was specified in this request. String query = request.getParameter("q"); if (query != null) { // 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();

// Now loop through the "rows" of the result set while(results.next()) { // For each row, display the the values for each column out.print(""); for(int i = 0; i < numcols; i++) out.print("" + results.getObject(i+1) + ""); out.println(""); } out.println(""); // end the table