java数据库连接池配置的几种方法(上)

发表于:2009-9-15 10:25

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:LIXG425    来源:CSDN博客

#
java

  今天遇到了关于数据源连接池配置的问题,发现有很多种方式可以配置,现总结如下,希望对大家有所帮助:(已Mysql数据库为例)

  一、Tomcat配置数据源:

  方式一:在WebRoot下面建文件夹META-INF,里面建一个文件context.xml,内容如下:

  <Context>

       <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"

       maxActive="50" maxIdle="30" maxWait="10000" logAbandoned="true"

       username="root" password="111111" driverClassName="com.mysql.jdbc.Driver"

       url="jdbc:mysql://localhost:3306/testdb" />

  </Context>

  方式二:在tomcat6.0的目录conf下面的context.xml中,修改原来的context标签,改成内容如下:

  <Context>

      <!-- Default set of monitored resources -->

      <WatchedResource>WEB-INF/web.xml</WatchedResource>

      <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"

      maxActive="50" maxIdle="30" maxWait="10000" logAbandoned="true"

      username="root" password="111111" driverClassName="com.mysql.jdbc.Driver"

      url="jdbc:mysql://localhost:3306/testdb" />

  </Context>

  方式三:在配置虚拟目录时,也就是在配置conf下面的server.xml时,在context标签内改成如下形式:

  <Context path="/WebRoot" reloadable="true" docBase="E:\workspace\DataSource\WebRoot" >

      <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"

      maxActive="50" maxIdle="30" maxWait="10000" logAbandoned="true"

      username="root" password="111111" driverClassName="com.mysql.jdbc.Driver"

      url="jdbc:mysql://localhost:3306/testdb" />

  </Context> 

  配置文件中Resource标签中各属性的含义:

  driverClassName - JDBC 所用到的数据库驱动的类全名.

  maxActive - 连接池在同一时刻内所提供的最大活动连接数。

  maxIdle - 连接池在空闲时刻保持的最大连接数.

  maxWait - 当发生异常时数据库等待的最大毫秒数 (当没有可用的连接时).

  password - 连接数据库的密码.

  url - 连接至驱动的URL. (为了向后兼容, DRIVERNAME也被允许.)

  user - 数据库用户名.

  各种配置方式的范围也应该是不一样的。我在这就不细说了,总之就是在Context标签下面配置个Resource标签即可。

  测试代码:

  Context initContext = new InitialContext();

  Context envContext  = (Context)initContext.lookup("java:/comp/env");

  DataSource ds = (DataSource)envContext.lookup("jdbc/test");

  System.out.println(ds.getConnection());

  打印出来不是null应该就成功了。

  注意,测试的时候要在tomcat内测试,也就是要在TOMCAT这个容器内(不要闲麻烦,写个简单的JSP页面测下,用个<%...%>就可以了,相当简单的)。不在tomcat这个容器里面测,会抛异常:

  ... javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

41/41234>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号