mySQL Servlet

The mySQL servlet connects to a mySQL database and reads some records, formatting them
into an HTML table.

Run mySQL servlet

Java Servlet Source Code

package mysql;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.net.*;

public class mySQLServlet extends HttpServlet
{
  private final String driverName = "org.gjt.mm.mysql.Driver";
    //general format of the connURL = "jdbc:mysql://host:port/database";
    //in this connURL example, the host=web8 and the database=dbname
  private final String connURL = "jdbc:mysql://web8/dbname";
  private final String username = "username";
  private final String password = "password";
  private static final String CONTENT_TYPE = "text/html";

  public String getPage()
  {
    Connection con = null;
    String html = "Records found in MediaTypes table:<br>\n";
    try
    {
      Class.forName(this.driverName).newInstance();
      con = DriverManager.getConnection(this.connURL, this.username, 
this.password); Statement statement = con.createStatement(); ResultSet rs = statement.executeQuery("SELECT * from mediaTypes"); html += "<br><TABLE BORDER=1>"; while (rs.next()) //FOUND RECORD! { html += "<TR><TD>" + rs.getString("mediaType") + "</TD></TR>\n"; } html += "</TABLE>"; return(html); } catch (SQLException sqle) { return (html + "<br><br>" + sqle.toString() + "<br>SQL State: " +
sqle.getSQLState()); } catch (ClassNotFoundException cnfe) { return (cnfe.toString()); } catch (Exception e) { return (e.toString()); } finally { try { if (con != null) con.close(); //try to close the db connection } catch (SQLException sqle) { return (sqle.toString()); } } } /**Initialize any global variables*/ public void init(ServletConfig config) throws ServletException { super.init(config); } /**Process the HTTP Get request*/ public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException { response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>mySQLServlet</title></head>"); out.println("<body bgColor=silver><h2>mySQL Servlet</h2>"); out.println("<h3>mySQL Servlet</h3>"); //construct a page from the mySQL data out.println(getPage()); out.println("</body></html>"); } /** do any cleanup */ public void destroy() { } }

 

{MainRegion}
   
Website copyright © 2002, SoftTech Design, Inc. All rights reserved worldwide.