Tomcat dbcp 数据库连接池 的配置及使用

环境:

① Tomcat 5.5.27

② postgresql8.4

1)添加jar包
tomcat中 TOMCAT_HOME/lib 下是公用jar包

dbcp需要3个jar包:Jakarta-Commons DBCP,Jakarta-Commons Collections,Jakarta-Commons Pool,
但是tomcat已经用1个naming-factory-dbcp.jar包含了这3个jar包,该包在 TOMCAT_HOME/lib 下,因此在tomcat下不需要再添加dbcp相关的3个包;但是,postgresql-8.4-703.jdbc4.jar 这个包是必须要拷贝到 TOMCAT_HOME/lib 下,即使你把这个包已经放在了你的工程下面的WEB-INF路径。

2)添加数据源
在 TOMCAT_HOME/conf/context.xml 中 添加数据源:
   

<Resource
      name="jdbc/XXXXXXXXXX"
      type="javax.sql.DataSource"
      driverClassName="org.postgresql.Driver"
      username="XXXXXXXXX"
      password="XXXXXXXXX"
      maxActive="100"
      maxIdle="40"
      minIdle="10"
      maxWait="5000"
      defaultAutoCommit="false"
      url="jdbc:postgresql://192.168.1.1:5432/XXXXXXXXXX"/>

 上面,打“XXXXXXXXXX”是需要根据自己项目的情况进行变更的,URL中的IP地址也是需要变更的,不能照搬啊。

在网上看教程的时候,一般都说还有下面这个步骤:

3)在web.xml 中引用数据源,即下面的“resource-ref”部分

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd"
    version="2.4">

    <display-name>JNDI Test</display-name>

    
    <description>A test for using of JNDI</description>
	<resource-ref>
		 <description>DB Connection</description>
		 <res-ref-name>jdbc/test</res-ref-name>
		 <res-type>javax.sql.DataSource</res-type>
		 <res-auth>Container</res-auth>
	</resource-ref>
    <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
      <welcome-file>index.html</welcome-file>
    </welcome-file-list>

</web-app>

但是,经过我实验,我发现这步不是必须的,大家根据自己情况进行设定吧。

3) 获取连接,下面是截取的我的测试类的部分代码

	/**
	 * connection pool
	 */
	private static DataSource ds;

	/**
	 * the instance of this util class self
	 */
	private static DBUtil instance;

	/**
	 * constructor
	 * 
	 * @throws Exception
	 */
	private DBUtil() throws Exception {
		try {
			// get the data source from the jndi context
			ds = (DataSource) ((Context) new InitialContext()
					.lookup("java:comp/env")).lookup("jdbc/XXXXXXXXXX");
		} catch (NamingException e) {
			throw e;
		}
	}

	public synchronized static DBUtil getInstance() throws Exception {
		if (instance == null) {
			instance = new DBUtil();
		}
		return instance;
	}

	/**
	 * get a database connection
	 * 
	 * @return a database connection
	 * @throws Exception database exception, if a database option error happens
	 */
	public Connection getConnection() throws Exception {
		try {
			// get a database connection from the connection pool
			Connection conn = ds.getConnection();
			return conn;
		} catch (SQLException e) {
			throw e;
		}
	}

获得数据库连接之后,你想干什么就干什么吧。

猜你喜欢

转载自rainbow702.iteye.com/blog/1562863