在tomcat文件中配置文件中加入:
<Context path="/DBTest" docBase="D:/rautinee work/db/"
debug="5" reloadable="true" crossContext="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_DBTest_log." suffix=".txt"
timestamp="true"/>
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/TestDB">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<!-- Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to 0 for no limit.
-->
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>
<!-- Maximum number of idle dB connections to retain in pool.
Set to 0 for no limit.
-->
<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>
<!-- Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>
<!-- MSSQLserver dB username and password for dB connections -->
<parameter>
<name>username</name>
<value>sa</value>
</parameter>
<parameter>
<name>password</name>
<value></value>
</parameter>
<!-- Class name for mssqlserver JDBC driver -->
<parameter>
<name>driverClassName</name>
<value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value>
</parameter>
<!-- The JDBC connection url for connecting to your mssqlserver dB.-->
<parameter>
<name>url</name>
<value>jdbc:microsoft:sqlserver://localhost:1433;databasename=Northwind</value>
</parameter>
</ResourceParams>
</Context>
连接池测试DBTest.java:
package foo;
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
public class DBTest {
String foo = "Not Connected";
String bar = "oo";
public void init() {
try{
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("Boom - No Context");
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/TestDB");
if (ds != null) {
Connection conn = ds.getConnection();
if(conn != null) {
foo = "Got Connection "+conn.toString();
Statement stmt = conn.createStatement();
ResultSet rst =
stmt.executeQuery("select * from orders");
if(rst.next()) {
foo=rst.getString("CustomerID");
bar=rst.getString("OrderID");
}
conn.close();
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
public String getFoo() { return foo; }
public String getBar() { return bar;}
}
页面显示:
<html>
<head>
<title>DB Test</title>
</head>
<body>
<%
foo.DBTest tst = new foo.DBTest();
tst.init();
%>
<h2>Ms sql server 2000 java search Results</h2>
Foo <%= tst.getFoo() %><br/>
Bar <%= tst.getBar() %>
</body>
</html>