This servlet uses a MySQL driver to query a MySQL database running on a remote machine. The database is presumed to already exist. In this "Hello, World" example, a single "canned" query is processed. A real application would include support for adding, deleting, searching on user-supplied data, updating, etc.
The example program that follows is similar to the one described elsewhere illustrating the use of the JDBC-ODBC Bridge to access a MS-ACCESS database. Consequently, identical segments of code not pertaining to interaction with a MySQL database have been deleted.
Note that the program uses a special MySql driver, referred to by org.gjt.mm.mysql.Driver. To interact with a MySQL database from another machine, such as your local development machine, you must place the jar file that contains this file on the classpath used by your server (e.g., Tomcat). You can find a copy of this jar file in the course tools directory.
Servlet
import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class jbsJDBCServletMysql extends HttpServlet { //***** Servlet access to MySQL data base public void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String url = "jdbc:mysql://eagle.cs.unc.edu/jbs_db"; String query = "SELECT * FROM Person " + "WHERE city = 'Chapel Hill'"; try { Class.forName ("org.gjt.mm.mysql.Driver"); Connection con = DriverManager.getConnection ( url, "your_logon", "your_password" ); Statement stmt = con.createStatement (); ResultSet rs = stmt.executeQuery (query); printResultSet ( resp, rs ); rs.close(); stmt.close(); con.close(); } // end try catch (SQLException ex) { while (ex != null) { /* System.out.println ("SQL Exception: " + ex.getMessage ()); ex = ex.getNextException (); */ } // end while } // end catch SQLException catch (java.lang.Exception ex) { ; } } // end doGet private void printResultSet ( HttpServletResponse resp, ResultSet rs ) throws SQLException { } // end printResultSet } // end jbsJDBCServletMysqlRun the Servlet