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 ^-^