Connect to Database in Servlet : Database « JSP « Java Tutorial






Jsp page

<%--
  Copyright (c) 2002 by Phil Hanna
  All rights reserved.
  
  You may study, use, modify, and distribute this
  software for any purpose provided that this
  copyright notice appears in all copies.
  
  This software is provided without warranty
  either expressed or implied.
--%>
<%@ page extends="com.jspcr.servlets.NutrientDatabaseServlet" %>
<%--
   This JSP page subclasses the NutrientDatabaseServlet
   parent class, which automatically loads the
   database driver and establishes the connection.
--%>
<%@ page import="java.io.*,java.sql.*" %>
<html>
<head>
<title>Food Groups</title>
</head>
<body>
<h1>Food Groups</h1>
<table border="1" cellpadding="3" cellspacing="0">
<tr><TH>Code</th><TH>Description</th></tr>
<%
   // Execute a query

   Statement stmt = con.createStatement();
   String sql = "SELECT * FROM FD_GROUP ORDER BY FDGP_DESC";
   ResultSet rs = stmt.executeQuery(sql);
   while (rs.next()) {
      String code = rs.getString(1);
      String desc = rs.getString(2);
%>
<tr>
   <td><%= code %></td>
   <td><%= desc %></td>
</tr>
<%
   }
   
   // Close the database objects

   rs.close();
   stmt.close();
%>
</table>
</body>
</html>

NutrientDatabaseServlet.java

/**
*  Copyright (c) 2002 by Phil Hanna
*  All rights reserved.
*  
*  You may study, use, modify, and distribute this
*  software for any purpose provided that this
*  copyright notice appears in all copies.
*  
*  This software is provided without warranty
*  either expressed or implied.
*/
package com.jspcr.servlets;

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

/**
* An example of a JSP superclass that can be selected with
* the <code>extends</code> attribute of the page
* directive.  This servlet automatically loads the
* JDBC-ODBC driver class when initialized and establishes
* a connection to the USDA nutrient database.
*/
public abstract class NutrientDatabaseServlet
   extends HttpServlet
   implements HttpJspPage
{
   protected Connection con;

   /**
   * Initialize a servlet with the driver
   * class already loaded and the database
   * connection established.
   */
   public void init(ServletConfig config)
      throws ServletException
   {
      super.init(config);
      try {
         Class.forName("com.mysql.jdbc.Driver");
         con = DriverManager.getConnection("jdbc:mysql://localhost/usda15");
      }
      catch (Exception e) {
         throw new UnavailableException(e.getMessage());
      }

      jspInit();
   }

   /**
   * Closes the database connection when
   * the servlet is unloaded.
   */
   public void destroy()
   {
      try {
         if (con != null) {
            con.close();
            con = null;
         }
      }
      catch (Exception ignore) {}

      jspDestroy();
      super.destroy();
   }

   /**
   * Called when the JSP is loaded.
   * By default does nothing.
   */
   public void jspInit() {}

   /**
   * Called when the JSP is unloaded.
   * By default does nothing.
   */
   public void jspDestroy() {}

   /**
   * Invokes the JSP's _jspService method.
   */
   public final void service(
         HttpServletRequest request,
         HttpServletResponse response)
      throws ServletException, IOException
   {
      _jspService(request, response);
   }

   /**
   * Handles a service request.
   */
   public abstract void _jspService(
         HttpServletRequest request,
         HttpServletResponse response)
      throws ServletException, IOException;
}
  Download:  ConnectToDatabaseInServlet.zip( 4 k)








23.52.Database
23.52.1.Make Database connection
23.52.2.Accessing the Database Table
23.52.3.Retrieve data in Database based on form input
23.52.4.Output ResultSet
23.52.5.Joining Tables
23.52.6.Creating a Table
23.52.7.Insert data to a table
23.52.8.Navigate Database Table With Javascript and JSP
23.52.9.Database Table Navigation Based On Form
23.52.10.Connect to Database in Servlet
23.52.11.Using Table Metadata
23.52.12.Output data in database as XML