使用dbcp做为数据库连接池

来源:互联网 发布:中级软件测评师真题 编辑:程序博客网 时间:2024/05/01 22:26

这个会用到的,今天弄了半天没弄好commons dbcp的配置

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:表示JNDIlookup是输入的资源名。

auth:是连接池管理权属性,Container表示容器管理。

name:表示你的连接池的名称也就是你要访问连接池的地址。

type:是对象的类型。

driverClassName:是数据库驱动的名称。

url:是数据库的地址。

username:是登陆数据库的用户名。

password:是登陆数据库的密码。

MaxActive:连接池的最大数据库连接数。设为0表示无限制。

maxIdle:最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。

maxWait :最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。

removeAbandoned:是否自我中断,默认是 false 

removeAbandonedTimeout:几秒后数据连接会自动断开,在removeAbandonedtrue,提供该值。

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;
    }

原创粉丝点击