
import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

/**
 * This is a simple example of an HTTP Servlet.  It responds to the GET
 * and HEAD methods of the HTTP protocol and queries a mysql database.
 * Note: Change the DATABASENAME, USERNAME, and PASSWORD in the connection
 *       string to gain functionality.  You may need to select a valid
 *       table as well.  ~Kattare
 */
public class TestMySQL extends HttpServlet
{ 
    /**
     * Handle the GET and HEAD methods by building a simple web page.
     * HEAD is just like GET, except that the server returns only the
     * headers (including content length) not the body we write.
     */
    public void doGet (HttpServletRequest request,
                       HttpServletResponse response) 
        throws ServletException, IOException
        {
          try {

                    // The newInstance() call is a work around for some
                    // broken Java implementations

                    Class.forName("org.gjt.mm.mysql.Driver").newInstance(); 

                    PrintWriter out;
                    String title = "Example - MySQL Servlet - Kattare";

                    // set content type and other response header fields first
                    response.setContentType("text/html");

                    // then write the data of the response
                    out = response.getWriter();
            
                    out.println("<HTML><HEAD><TITLE>");
                    out.println(title);
                    out.println("</TITLE></HEAD><BODY bgcolor=\"#FFFFFF\">");
                    out.println("<H1>" + title + "</H1><BR>");

                    Connection Conn = DriverManager.getConnection("jdbc:mysql://mysql.kattare.com/test?user=test&password=test");

                    Statement Stmt = Conn.createStatement();

                    ResultSet RS = Stmt.executeQuery("SELECT * from test");

                    while (RS.next()) {
                          out.println(RS.getString(1) + " - " + RS.getString(2) + "<BR>");
                    }

                    out.println("</BODY></HTML>");
                    out.close();

                    // Clean up after ourselves
                    RS.close();
                    Stmt.close();
                    Conn.close();
           }
           catch (SQLException E) {
                System.out.println("SQLException: " + E.getMessage());
                System.out.println("SQLState:     " + E.getSQLState());
                System.out.println("VendorError:  " + E.getErrorCode());
           }
           catch (Exception E) {
               PrintWriter out;
               response.setContentType("text/html");
               out = response.getWriter();            
               out.println("Unable To Load Driver...");
               out.close();
           }
        }
}
 
