首页 > 开发 > Tomcat > 正文

Tomcat 的数据库连接池设置与应用

2020-02-05 13:42:38
字体:
来源:转载
供稿:网友

1.将数据库驱动程序的jar文件放在tomcat的 common/lib 中;

2.在server.xml中设置数据源,以mysql数据库为例,如下:
在<globalnamingresources> </globalnamingresources>节点中加入,
      <resource
      name="jdbc/dbpool"
      type="javax.sql.datasource"
      password="root"
      driverclassname="com.mysql.jdbc.driver"
      maxidle="2"
      maxwait="5000"
      username="root"
      url="jdbc:mysql://127.0.0.1:3306/test"
      maxactive="4"/>
   属性说明:name,数据源名称,通常取”jdbc/xxx”的格式;
            type,”javax.sql.datasource”;
            password,数据库用户密码;
            driveclassname,数据库驱动;
            maxidle,最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连
                     接将被标记为不可用,然后被释放。设为0表示无限制。
            maxactive,连接池的最大数据库连接数。设为0表示无限制。
            maxwait ,最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示
                     无限制。

3.在你的web应用程序的web.xml中设置数据源参考,如下:
  在<web-app></web-app>节点中加入,
  <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>
  子节点说明: description,描述信息;
               res-ref-name,参考数据源名字,同上一步的属性name;
               res-type,资源类型,”javax.sql.datasource”;
               res-auth,”container”;
               res-sharing-scope,”shareable”;

4.在web应用程序的context.xml中设置数据源链接,如下:
  在<context></context>节点中加入,
  <resourcelink
   name="jdbc/dbpool" 
   type="javax.sql.datasource" 
   global="jdbc/dbpool"/>
   属性说明:name,同第2步和第3步的属性name值,和子节点res-ref-name值;
             type,同样取”javax.sql.datasource”;
             global,同name值。
 
至此,设置完成,下面是如何使用数据库连接池。
1.建立一个连接池类,dbpool.java,用来创建连接池,代码如下:
import javax.naming.context;
import javax.naming.initialcontext;
import javax.naming.namingexception;
import javax.sql.datasource;

public class dbpool {
    private static datasource pool;
    static {
         context env = null;
          try {
              env = (context) new initialcontext().lookup("java:comp/env");
              pool = (datasource)env.lookup("jdbc/dbpool");
              if(pool==null) 
                  system.err.println("'dbpool' is an unknown datasource");
               } catch(namingexception ne) {
                  ne.printstacktrace();
          }
      }
    public static datasource getpool() {
        return pool;
    }
}

2.在要用到数据库操作的类或jsp页面中,用dbpool.getpool().getconnection(),获得一个connection对象,就可以进行数据库操作,最后别忘了对connection对象调用close()方法,注意:这里不会关闭这个connection,而是将这个connection放回数据库连接池。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表