TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
下面用到的连接代理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.
*/
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){
//......
}
源码下载:http://file.javaxxz.com/2014/10/10/005711125.zip |
|