FileDocCategorySizeDatePackage
RawSQLServlet.javaAPI DocExample3193Mon Mar 08 22:28:04 GMT 2004None

RawSQLServlet

public class RawSQLServlet extends HttpServlet
Process a raw SQL query; use ResultSetMetaData to format it.

Fields Summary
protected ServletContext
application
The application-wide servlet context
protected Connection
conn
The DB connection object
protected Statement
stmt
The JDBC statement object
Constructors Summary
Methods Summary
public voiddestroy()

		try {
			conn.close();	// All done with that DB connection
		} catch (SQLException ex) {
			log(getClass() + ": destroy: " + ex);
		}
	
public voiddoPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
Do the SQL query


		String query = request.getParameter("sql");

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		if (query == null) {
			out.println("<b>Error: malformed query, contact administrator</b>");
			return;
		}

		// NB MUST also check for admin privs before proceding!

		try {	// SQL
			out.println("<p>Your query: <b>" + query + "</b></p>");
			stmt.execute(query);
			ResultSet rs = stmt.getResultSet();
			if (rs == null) {
				// print updatecount
				out.println("<p>Result: updateCount = <b>" + 
					stmt.getUpdateCount() + "</p>");
			} else {
				// process resultset

				out.println("<br>Your response:");

				ResultSetMetaData md = rs.getMetaData();
				int count = md.getColumnCount();
				out.println("<table border=1>");
				out.print("<tr>");
				for (int i=1; i<=count; i++) {
					out.print("<th>");
					out.print(md.getColumnName(i));
				}
				out.println("</tr>");
				while (rs.next()) {
					out.print("<tr>");
					for (int i=1; i<=count; i++) {
						out.print("<td>");
					out.print(rs.getString(i));
				}
				out.println("</tr>");
				}
			}
			out.println("</table>");
			// rs.close();
		} catch (SQLException ex) {
			out.print("<B>" + getClass() + ": SQL Error:</B>\n" + ex);
			out.print("<pre>");
			ex.printStackTrace(out);
			out.print("</pre>");
		}
	
public voidinit()
Initialize the servlet.

		application = getServletConfig().getServletContext();
		String driver = null;
		try {

			driver = application.getInitParameter("db.driver");
			Class.forName(driver);

			// Get the connection
			log(getClass() + ": Getting Connection");
			Connection conn = DriverManager.getConnection (
				application.getInitParameter("db.url"),
				application.getInitParameter("db.user"),
				application.getInitParameter("db.password"));


			log(getClass() + ": Creating Statement");
			stmt = conn.createStatement();
		} catch (ClassNotFoundException ex) {
			log(getClass() + ": init: Could not load SQL driver " + driver);
		} catch (SQLException ex) {
			log(getClass() + ": init: SQL Error: " + ex);
		}