api:
http://egee-jra1-integration.web.cern.ch/egee-jra1-integration/repository/commons-dbcp/1.1/share/docs/apidocs/index.html
jar包&源碼:
http://www.jdocs.com/dbcp/1.2.1/org/apache/commons/dbcp/BasicDataSource.html
對于DBCP連接池的使用:
1.要在tomcat下的conf包中的server.xml中加入數據庫連接池配置信息:
a.在<Host>標簽下加入
<Context path="/myweb" docBase="D:"apache-tomcat-6.0.18"webapps"myweb" >
<Resource auth="Container" name="jdbc/jlndb" type="javax.sql.DataSource"
factory="org.apache.commons.dbcp.BasicDataSourceFactory"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:JLNDB"
username="db"
password="db"
maxActive="10000"
maxIdle="10000"
maxWait="10000"
removeAbandoned="true"
removeAbandonedTimeOut="10"
logAbandoned="true"/>
</Context>
注釋:
path指定訪問Web應用的URL入口,注意/myweb,而不是myweb,必須有/。
docBase:表示的項目的具體路徑。
< Resource >元素為JNDI,在lookup是要查找的資源,
name:表示JNDI在lookup是輸入的資源名。
auth:是連接池管理權屬性,Container表示容器管理。
name:表示你的連接池的名稱也就是你要訪問連接池的地址。
type:是對象的類型。
driverClassName:是數據庫驅動的名稱。
url:是數據庫的地址。
username:是登陸數據庫的用戶名。
password:是登陸數據庫的密碼。
MaxActive:連接池的最大數據庫連接數。設為0表示無限制。
maxIdle:最大空閑數,數據庫連接的最大空閑時間。超過空閑時間,數據庫連接將被標記為不可用,然后被釋放。設為0表示無限制。
maxWait :最大建立連接等待時間。如果超過此時間將接到異常。設為-1表示無限制。
removeAbandoned:是否自我中斷,默認是 false 。
removeAbandonedTimeout:幾秒后數據連接會自動斷開,在removeAbandoned為true,提供該值。
logAbandoned:是否記錄中斷事件, 默認為 false。
注意:
其中factory="org.apache.commons.dbcp.BasicDataSourceFactory" 也可以配置
factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
*maxActive:最大連接數據庫連接數,設 0 為沒有限制
*maxIdle:最大等待連接中的數量,設 0 為沒有限制
*maxWait:最大等待毫秒數, 單位為 ms, 超過時間會出錯誤信息
b.在web.xml中加入配置信息:
數據庫資源映射信息
<resource-ref id="db">
<description>DB Connection</description>
<res-ref-name>jdbc/jlndb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
其中id可以不寫。
注意:這里我沒有配置web.xml也成功了。
c.添加架包,使用dbcp需要3個包:
common-dbcp.jar,
common-pool.jar,
common-collections.jar
數據庫的驅動包:具體看數據庫而定
2.需要一個servlet來初始化監視器
package com.handson.bbs.servlet;

import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.dbcp.BasicDataSource;

import com.handson.commons.jdbc.DataSourceProvider;

/** *//**
* **********************************************
* @description 通過監視器,在項目啟動時初始化連接池
* @author Gavin.lee
* @date Jun 27, 2009 1:13:28 PM
* @version 1.0
***********************************************
*/

public class DBCPInitListener implements ServletContextListener
{
//釋放連接池的資源

public void contextDestroyed(ServletContextEvent event)
{
BasicDataSource ds = (BasicDataSource)DataSourceProvider.getInstance().getDataSource();

if(ds != null)
{

try
{
ds.close();

} catch (SQLException e)
{
e.printStackTrace();
}
}
}

//初始化連接池

public void contextInitialized(ServletContextEvent event)
{

try
{
Context cxt = new InitialContext();
BasicDataSource ds = (BasicDataSource)cxt.lookup("java:/comp/env/jdbc/dataSource");
DataSourceProvider.getInstance().initDataSource(ds);

} catch (NamingException e)
{
e.printStackTrace();
}
}

}
3.web.xml配置
監視器
<listener>
<listener-class>com.handson.bbs.servlet.DBCPInitListener</listener-class>
</listener>
4.DataSourceProvider用來初始化BasicDataSource
package com.handson.commons.jdbc;

import javax.sql.DataSource;

/** *//**
* **********************************************
* @description 單態類初始化數據源
* @author Gavin.lee
* @date Jun 27, 2009 1:19:21 PM
* @version 1.0
***********************************************
*/

public class DataSourceProvider
{
private DataSource ds;
private static DataSourceProvider instance;

private DataSourceProvider()
{
}

public static DataSourceProvider getInstance()
{

if(instance == null)
{
instance = new DataSourceProvider();
}
return instance;
}

public void initDataSource(DataSource ds)
{
this.ds = ds;
}


public DataSource getDataSource()
{
return ds;
}
}

5.DAO層可以使用DBCP連接池資源了,這里為了擴展,封裝了一個DBUtil類(不喜歡的話可以直接在DAO通過連接DataSourceProvider初始化資源)
package com.handson.commons.jdbc;

import java.io.*;
import java.sql.*;

import javax.sql.*;

/** *//**
* **********************************************
* @description DBUtil類,為擴展用
* @author Gavin.lee
* @date Jun 27, 2009 1:23:57 PM
* @version 1.0
***********************************************
*/

public class DBUtil
{
private Connection conn = null;
private PreparedStatement prepStmt = null;

public DBUtil(String sql) throws SQLException
{
DataSourceProvider provider = DataSourceProvider.getInstance();
this.conn = provider.getDataSource().getConnection();
prepStmt = conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}

public DBUtil(Connection conn, String sql) throws SQLException
{
this.conn = conn;
prepStmt = conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}

public DBUtil(DataSource ds, String sql) throws SQLException
{
conn = ds.getConnection();
prepStmt = conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}

public Connection getConnection()
{
return conn;
}

public PreparedStatement getPreparedStatement()
{
return prepStmt;
}

public boolean execute() throws SQLException
{
if(prepStmt == null)
return false;
return prepStmt.execute();
}

public ResultSet executeQuery() throws SQLException
{
return prepStmt.executeQuery();
}

public int executeUpdate() throws SQLException
{

if(prepStmt == null)
{
return -1;
}
return prepStmt.executeUpdate();
}

public void close()
{

try
{

if (prepStmt != null)
{
prepStmt.close();
prepStmt = null;
}

if(conn != null)
{
conn.close();
conn = null;
}

} catch (Exception e)
{
e.printStackTrace();
}
}

public void setString(int index,String value) throws SQLException
{
prepStmt.setString(index,value);
}

public void setInt(int index,int value) throws SQLException
{
prepStmt.setInt(index,value);
}

public void setBoolean(int index,boolean value) throws SQLException
{
prepStmt.setBoolean(index,value);
}

public void setDate(int index,Date value) throws SQLException
{
prepStmt.setDate(index,value);
}

public void setDate(int index, java.util.Date value) throws SQLException
{
java.sql.Date date = new java.sql.Date(value.getTime());
prepStmt.setDate(index, date);
}

public void setTime(int index,Time value) throws SQLException
{
prepStmt.setTime(index,value);
}

public void setTimestamp(int index,Timestamp value) throws SQLException
{
prepStmt.setTimestamp(index,value);
}

public void setLong(int index,long value) throws SQLException
{
prepStmt.setLong(index,value);
}

public void setFloat(int index,float value) throws SQLException
{
prepStmt.setFloat(index,value);
}

public void setObject(int index, Object obj) throws SQLException
{
prepStmt.setObject(index, obj);
}

/** *//**
* File file = new File("test/data.txt");
* int fileLength = file.length();
* InputStream fin = new java.io.FileInputStream(file);
* mysql.setBinaryStream(5,fin,fileLength);
*/

public void setBinaryStream(int index,InputStream in,int length) throws SQLException
{
prepStmt.setBinaryStream(index,in,length);
}

public void commit()
{

try
{
conn.commit();

} catch(Exception e)
{
e.printStackTrace();
}
}

public void rollback()
{

try
{
conn.rollback();

} catch(Exception e)
{
e.printStackTrace();
}
}

public static void main(String[] args)
{
}


}
6.具體的一個使用實例
private DataSource ds;

public ForumDAO()
{
this.ds = DataSourceProvider.getInstance().getDataSource();
}

/**//*
* 通過帖子的主題來查找帖子
* (non-Javadoc)
* @see com.handson.bbs.dao.IForumDAO#searchForumsBySubject(java.lang.String)
*/

public List<Forum> searchForumsBySubject(String subject)
{
String sql = "select * from forum where subject like '%" + subject + "%'";
DBUtil db = null;
List<Forum> forums = null;

try
{
db = new DBUtil(ds,sql);
//db.setString(1,subject);
ResultSet rs = db.executeQuery();
Forum forum = null;

while(rs.next())
{
forums = new ArrayList<Forum>();
forum = this.populate(rs);
forums.add(forum);
}

}catch(Exception e)
{
e.printStackTrace();

}finally
{
db.close();
}
return forums;
}
