DDConnectionBroker 轻量级的数据库连接池

来源:互联网 发布:c语言sleep怎么用 编辑:程序博客网 时间:2024/05/22 05:08

在servlet中用连接池DDConnectionBroker

下面用到的连接代理DDConnectionBroker,请从http://opensource.devdaily.com/下载其jar文件DDConnectionBroker.jar。

先写一个Singleton(单态)类,以便在服务器中共享连接池。

package examples;

import com.devdaily.opensource.database.DDConnectionBroker;

import java.io.*;

import java.sql.*; 
 
  /**
  /* This is our class that will be shared across all of the
   * servlets for the 'Lavender' database. It is a singleton,
   * and also works as an adapter to the connection broker
   * class that we are using.
  */

<script type="text/javascript"><!--google_ad_client = "pub-1832179689702023";google_ad_width = 336;google_ad_height = 280;google_ad_format = "336x280_as";google_ad_type = "text_image";//2007-01-10: 336_280google_ad_channel = "7111701428";google_color_border = "FFFFFF";google_color_bg = "FFFFFF";google_color_link = "0000FF";google_color_text = "000000";google_color_url = "3D81EE";//--></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script>

  public class LavenderDBSingleton
  {
 
    private DDConnectionBroker m_broker;
    private static LavenderDBSingleton m_singleton = null;
 
    private LavenderDBSingleton()
    {
       /*
        * We will put all of our database-specific information
        * here. Please note that we could have read this
        * information from a properties file.
        */
 
         String driver         = "sun.jdbc.odbc.JdbcOdbcDriver";
         String url            = "jdbc:odbc:Lavender";
         String uname = "";
         String passwd = ""; 
 
         int minConnections  = 1;
         int maxConnections  = 10;
         long timeout        = 100;
         long leaseTime      = 60000;
         String logFile        = "c:/tmp/ConnectionPool.log"; 
         
         try
         {
             m_broker = new DDConnectionBroker(driver,
                                             url, uname, passwd,
                                             minConnections,
                                             maxConnections,
                                             timeout,
                                             leaseTime,
                                             logFile);
         }
         catch (SQLException se)
         {
             System.err.println( se.getMessage() );
         }
    }
    /** 
     *  getInstance() returns the class, instantiating it
     *  if there is not yet an instance in the VM. 
     */
    public static LavenderDBSingleton getInstance()
    {
        if (m_singleton == null)
        {
            m_singleton = new LavenderDBSingleton(); 
        }
        
        return (m_singleton); 
    }
 
    /*
     * calls getConnection() on the broker class 
     */
    public synchronized Connection getConnection() throws Exception 
    {
        if (m_broker == null)
        {
            throw new Exception("Can't get Connection broker!"); 
        }
        return (m_broker.getConnection());
    }
 
    /*
     * frees the connection from the broker class
     */
    public synchronized void freeConnection(Connection con) 
     throws Exception 
    {
        if (m_broker == null )
        {
            throw new Exception("Can't get Connection broker!"); 
        }
        m_broker.freeConnection(con); 
    }
  }

下面是测试代码:

package examples;

import java.io.*;
import java.sql.*;
import java.text.*;
import java.util.*; 
import javax.servlet.*;
import javax.servlet.http.*;

public class BestQueryServlet extends HttpServlet
{
  //only set in the init() method, so concurrency
  //issues should be fine. 
  private LavenderDBSingleton m_dbsingleton = null;

  public void init()
  {
    /*
     * This will instantiate it within the Servlet's
     * virtual machine if it hasn't already. If it 
     * has, we have the instance of it. 
     */
    m_dbsingleton = LavenderDBSingleton.getInstance();   
  }
  /**
   *  simply forwards all to doPost() 
   */
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
  throws IOException, ServletException
  {
    doPost(request,response); 
  }

  /**
   * The main form! 
   */
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
  throws IOException, ServletException
  {
    PrintWriter out = response.getWriter(); 

    out.println("<TITLE>Internal Inventory Check</TITLE>"); 
    out.println("<BODY BGCOLOR='white'>");
    out.println("<H1>Lavender Fields Farm Internal Inventory</H1>");

    //show the date. 
    SimpleDateFormat sdf =new SimpleDateFormat ("EEE, MMM d, yyyy h:mm a"); 
    java.util.Date newdate = new java.util.Date(Calendar.getInstance().getTime().getTime()); 
    String datestring = sdf.format(newdate); 

    out.println("<H3>Inventory as of: " + datestring + "</H3>"); 

    out.println("<TABLE BORDER=1>");
    out.println("<TR><TD BGCOLOR='yellow'>" +
                "<B><CENTER>Name</CENTER></B></TD>" +
                "<TD BGCOLOR='yellow'><B>" +
                "<CENTER>Description</CENTER></B></TD>" +
                "<TD BGCOLOR='yellow'><B>" +
                "<CENTER>Inventory Amount</CENTER></B></TD></TR>");

    //Load the inventory from the database. 

    try
    {

      Connection con = m_dbsingleton.getConnection();
      if (con == null)
      {
        out.println("<B>There are currently database problems. " +
                    "Please see your administrator for details.</B>");
        return; 
      }


      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("select * from Inventory");

      while (rs.next())
      {
        String amtString = ""; 
        int amt = rs.getInt("Amount"); 
        if (amt < 50)
          amtString ="<TD><CENTER><FONT COLOR='RED'>" + 
                       amt + "</FONT></CENTER></TD>";
        else
          amtString ="<TD><CENTER>" + 
                       amt + "</CENTER></TD>"; 

        out.println("<TR><TD><CENTER>" + rs.getString("Name") + 
                    "</CENTER></TD><TD><CENTER>" + 
                    rs.getString("Description") + 
                    "</CENTER></TD>" + amtString + "</TR>");                                   
      }
      rs.close();
      out.println("</TABLE><HR>Items in <FONT COLOR='red'>RED</FONT>" +
                  " denote a possible low inventory. Click Here to " +
                  " contact <A HREF='mailto:mgmt@localhost'>" +
                  "MANAGEMENT</A> to order more supplies.");

      //Free the connection!
      m_dbsingleton.freeConnection( con );

    } 
    catch (Exception e)
    {
      out.println("There were errors connecting to the database." +
                  " Please see your systems administrator for details.");
      e.printStackTrace(); 
    }

  }

}

在我们的应用中需要连接时,只需简单地象下面这样:

  LavenderDBSingleton singleton=LavenderDBSingleton.getInstance();
  Connection con=singleton.getConnection();
  try{
      Statement stmt=con.createStatement();
      ResultSet rs=stmt.executeQuery("select * from Inventory");
      //do something
      singleton.freeConnection(con);
 }catch(Exception e){
   //......
 }