tomcat配置数据库连接池

1.server.xml中 

在host标签下增加

<!--configure jndi database pool-->
<Context path="/test_jndi" docBase="D:/softSetup/jakarta-tomcat-5.0.19/webapps/test_jndi" debug="0" reloadable="true" crossContext="true">
<Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_quality_log." suffix=".txt" timestamp="true"/>
<Resource name="jdbc/connectDB" auth="Container" type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/connectDB">
 <parameter>
  <name>maxActive</name>
  <!-- Maximum number of DB connections in pool.Set to 0 for no limit. -->
  <value>100</value>
 </parameter>
 <parameter>
  <name>maxIdle</name>
  <!-- Maximum number of idle DB connections to retain in pool.Set to 0 for no limit. -->
  <value>30</value>
 </parameter>
 <parameter>
  <name>maxWait</name>
  <!-- Maximum time to wait for a DB connection to become available in ms.An exception is thrown if this timeout is exceeded.Set to -1 to wait indefinitely. -->
  <value>10000</value>
 </parameter>
 <parameter>
  <name>removeAbandoned</name>
  <!-- Abandoned DB connections are removed and recycled -->
  <value>true</value>
 </parameter>
 <parameter>
  <name>removeAbandonedTimeout</name>
  <!-- Use the removeAbandonedTimeout parameter to set the number of seconds a DB connection has been idle before it is considered abandoned.  -->
  <value>60</value>
 </parameter>
 <parameter>
  <name>logAbandoned</name>
  <!-- Log a stack trace of the code which abandoned -->
  <value>false</value>
 </parameter>
 <parameter>
  <name>factory</name>
  <!--DBCP Basic Datasource Factory -->
  <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
 </parameter>
 <parameter>
  <name>username</name>
  <!-- Database User Name -->
  <value>root</value>
 </parameter>
 <parameter>
  <name>password</name>
  <!-- User Password -->
  <value>pwd</value>
 </parameter>
 <parameter>
  <name>driverClassName</name>
  <!-- Database Driver Class Name -->
  <!--<value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value>
   <value>oracle.jdbc.driver.OracleDriver</value>
    <value>org.gjt.mm.mysql.Driver</value>--> <!---for mysql,both config style are okay-->
    <value>com.mysql.jdbc.Driver</value>
 </parameter>
 <parameter>
  <name>url</name>
  <!-- Database Address -->
  <!--<value>jdbc:microsoft:sqlserver://localhost:1433;databasename=test</value>
  <value>jdbc:oracle:thin:@localhost:1521:ora8</value>-->
  <value>jdbc:mysql://localhost:3306/sample</value>
 </parameter>
</ResourceParams>
</Context>
 <!--configure jndi database pool-->       

注析:
dbcp.maxActive         最大有效的数据库连接数
dbcp.maxIdle           最大空闲的数据库连接数
dbcp.maxWait           数据库连接最大可空闲时间(以毫秒为单位,设为-1则关    闭)
removeAbandoned  true      通过配置DBCP数据源中的参数removeAbandoned来保证删除被遗弃的连接使其可以被重新利用。为ResourceParams(见下文的数据源配置)标签添加参数removeAbandoned,通过这样配置的以后当连接池中的有效连接接近用完时DBCP将试图恢复和重用被遗弃的连接。这个参数的值默认是false。
removeAbandonedTimeout  60 通过设置removeAbandonedTimeout来设置被遗弃的连接的超时的时间,即当一个连接连接被遗弃的时间超过设置的时间时那么它会自动转换成可利用的连接。默认的超时时间是300秒。
logAbandoned     true      设置logAbandoned参数,这个参数的用处我没能够理解它的意义所以提供原文供大家参考。The logAbandoned parameter can be set to true if you want DBCP to log a stack trace of the code which abandoned the dB connection resources。这个参数默认为false。

2.在web应用web.xml中  

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
 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
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <!--add for database pool-->
 <resource-ref>
      <description>postgreSQL Datasource example</description>
      <res-ref-name>jdbc/connectDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
        </resource-ref>
        <!--add for database pool-->
</web-app>

3.将数据库驱动jar(我的mysql是mysql-connector-java-3.0.11-stable-bin.jar)拷贝到tomcat的common/lib下

4.在web页面应用:

<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.naming.Context"%>
<%@ page import="javax.naming.InitialContext"%>
<%@ page import="javax.sql.DataSource"%>
<html>
<body>   
<%
 //Class.forName("org.gjt.mm.mysql.Driver").newInstance();
 //String url = "jdbc:mysql://localhost:3306/sample?user=soft&password=soft1234&useUnicode=true&characterEncoding=8859_1"; 
 Context initContext = new InitialContext();
 Context envContext  = (Context)initContext.lookup("java:/comp/env");
 DataSource ds = (DataSource)envContext.lookup("jdbc/connectDB");
 Connection conn = null;
 Statement stmt = null;
 ResultSet rs = null;
 
 try{ 
  conn = ds.getConnection();
  out.println("conn is:"+conn+"<br/>");
  //testDB为你的数据库名
  //Connection conn= DriverManager.getConnection(url);
  stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
  String sql="select * from t_user where id=3";
  rs=stmt.executeQuery(sql);
  while(rs.next()) {
  out.print("您的第一个字段内容为:"+rs.getString(1)+"<br/>");
  out.print("您的第二个字段内容为:"+rs.getString(2)+"<br/>");
  }
  out.print("数据库操作成功,恭喜你");
  }catch(Exception   e)  
  {     out.print(e);
  }finally {
    // Always make sure result sets and statements are closed,
    // and the connection is returned to the pool
    if (rs != null) {
      try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
      rs = null;
    }
    if (stmt != null) {
      try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
      stmt = null;
    }
    if (conn != null) {
      try { conn.close(); } catch (SQLException e) { e.printStackTrace(); }
      conn = null;
    }
  }
%>
</body>
</html>

5.在IE里输入:http://localhost:8080/test_jndi/test.jsp
 打印:
 conn is:org.apache.commons.dbcp.PoolableConnection@167e3a5
 您的第一个字段内容为:3
 您的第二个字段内容为:t1
 数据库操作成功

6.OK ^-^

你可能感兴趣的:(tomcat,数据库,exception,数据库连接池,null,database)