- <pre class="html" name="code">1.将数据库驱动程序的JAR文件放在Tomcat的 common/lib 中;
- </pre><pre class="html" name="code">2.在server.xml中设置数据源,以MySQL数据库为例,如下:
- 在<GlobalNamingResources> </GlobalNamingResources>节点中加入,
- </pre><pre class="html" name="code"><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"/>
- </pre><pre class="html" name="code">属性说明:name,数据源名称,通常取”jdbc/XXX”的格式;
- type,”javax.sql.DataSource”;
- password,数据库用户密码;
- driveClassName,数据库驱动;
- maxIdle,最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。
- MaxActive,连接池的最大数据库连接数。设为0表示无限制。
- maxWait ,最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。</pre><pre class="html" name="code">
- 3.在你的web应用程序的web.xml中设置数据源参考,如下:
- 在<web-app></web-app>节点中加入,
- </pre><pre class="html" 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="html" name="code"> 子节点说明: </pre><pre class="html" name="code"> description,描述信息;
- res-ref-name,参考数据源名字,同上一步的属性name;
- res-type,资源类型,”javax.sql.DataSource”;
- res-auth,”Container”;
- res-sharing-scope,”Shareable”;
- </pre><pre class="html" name="code">4.在web应用程序的context.xml中设置数据源链接,如下:
- 在<Context></Context>节点中加入,
- </pre><pre class="html" name="code"><ResourceLink
- name="jdbc/DBPool"
- type="javax.sql.DataSource"
- global="jdbc/DBPool"/>
- </pre><pre class="html" name="code">属性说明:</pre><pre class="html" name="code"> name,同第2步和第3步的属性name值,和子节点res-ref-name值;
- type,同样取”javax.sql.DataSource”;
- global,同name值。
- 至此,设置完成,下面是如何使用数据库连接池。
- </pre><pre class="html" name="code">1.建立一个连接池类,DBPool.java,用来创建连接池,代码如下:
- <pre class="java" name="code">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;
- }
- } </pre><br>
- <pre></pre>
- <pre class="html" name="code">2.在要用到数据库操作的类或jsp页面中,用DBPool.getPool().getConnection(),获得一个Connection对象,就可以进行数据库操作,最后别忘了对Connection对象调用close()方法,注意:这里不会关闭这个Connection,而是将这个Connection放回数据库连接池。
- </pre><br>
- <pre></pre>
- <pre></pre>
- </pre>
本文详细介绍如何在Tomcat服务器中配置MySQL数据库连接池,包括放置JAR文件、设置server.xml和web.xml中的数据源参数,以及在应用程序中获取和使用连接。
7628

被折叠的 条评论
为什么被折叠?



