首页 >> 文档 >> 服务器技术

tomcat数据库连接池配置教程

发布日期:2008-07-10最近更新:2008-07-10来源:BHCODE作者:

配置Tomcat数据池分为三步:

一、修改Tomcat安装目录下conf->server.xml文件的<GlobalNamingResources>节点下添加


<Resource 
 
    name="jdbc/DBPool" 
 
    type="javax.sql.DataSource" 
 
    password="root" 
 
    driverClassName="com.mysql.jdbc.Driver" 
 
    maxIdle="30" 
 
    maxWait="10000" 
 
    username="root" 
 
    url="jdbc:mysql://localhost/skynet" 
 
    maxActive="100"/> 

  <Resource

      name="jdbc/DBPool"

      type="javax.sql.DataSource"

      password="root"

      driverClassName="com.mysql.jdbc.Driver"

      maxIdle="30"

      maxWait="10000"

      username="root"

      url="jdbc:mysql://localhost/skynet"

      maxActive="100"/>其中name中的DBPool代表连接池的名称,也就是你要在程序中要使用的连接池的名称,type代表当前节点的类型,driverClassName表示数据库驱动,maxIdle为允许的最大空余连接,maxWait表示允许的最大连接数,url表示用户连接的连接参数,maxActive表示允许的最大活动连接数。

二、将对应的驱动.jar包拷贝到Tomcat的安装目录下common->lib下

三、修改conf->context.xml文档,在<context></context>节点下面添加如下代码:


<ResourceLink 
 
  name="jdbc/DBPool"   
 
  type="javax.sql.DataSource"   
 
  global="jdbc/DBPool"/> 

 <ResourceLink

   name="jdbc/DBPool"

   type="javax.sql.DataSource"

   global="jdbc/DBPool"/>
四、修改web应用程序里面的web.xml,添加<PRE class=xml name="code">  <resource-ref> 
 
    <description>MySQL DB Connection Pool</description> 
 
    <res-ref-name>jdbc/DBPool</res-ref-name> 
 
    <res-type>javax.sql.DataSource</res-type> 
 
    <res-auth>Container</res-auth> 
 
    <res-sharing-scope>Shareable</res-sharing-scope> 
 
 </resource-ref></PRE> 
<PRE class=xml name="code">其中<res-ref-name>表示数据池的名称,<res-type>表示数据池的类型,<res-auth>表示数据池的拥有者。</PRE> 
<PRE class=xml name="code"> </PRE> 
<PRE class=xml name="code">五、向数据池申请链接,代码如下:</PRE> 
<PRE class=xml name="code"><PRE class=java name="code"><%  
 
   try  
 
   {  
 
       Context initCtx=new InitialContext();  
 
       DataSource ds = (DataSource)initCtx.lookup("java:comp/env/jdbc/DBPool");  
 
       Connection conn=ds.getConnection();  
 
       if(conn != null)  
 
       out.println("连接建立成功!!");  
 
    }  
 
    catch(Exception e)  
 
    {  
 
        e.printStackTrace();  
 
    }  
 
%></PRE> 
<PRE class=java name="code">创建连接之后对应的conn和通过JDBC建立的Connection使用方法一样,最后别忘了使用完之后归还连接。</PRE> 
</PRE> 

本周推荐
MORE
热点关注
MORE