Tomcat5+Mssql server 2000数据库连接池配置之旅

来源:百度文库 编辑:神马文学网 时间:2024/04/23 18:45:02
Tomcat相信大家已经很熟悉了,作为一种免费而强大的java web server,得到了很多java爱好者的青睐,最新版本的tomcat5支持servlet2.4和jsp2.0,今天我将采用Tomcat5和Ms sqlserver 000一起来开始数据库连接池配置之旅。
需要的准备
1、jdk 我使用的版本1.4.01
2、Tomcat 5 我使用的是5.0.16版本 下载地址:http://jakarta.apache.org/site/binindex.cgi
3、Mssql server 2000 数据库
4、Mssql server 2000的官方jdbc driver ,可以到微软的官方网站免费下载
好了在安装完上面的软件之后,就进入配置实战了:)
一、找到jdbc的安装目录,把lib目录下面的msbase.jar和mssqlserver.jar、msutil.jar三个文件一起copy到$CATALINA_HOME/common/lib/($CATALINA_HOME代表的是你的tomcat5的安装目录)
二、用文本编辑器,我这是使用editplus(她可是我的挚爱奥)打开$CATALINA_HOME/conf/server.xml文件,找到配置context的地方,把下面的代码
粘贴到文件里面
debug="5" reloadable="true" crossContext="true">
prefix="localhost_DBTest_log." suffix=".txt"
timestamp="true"/>
auth="Container"
type="javax.sql.DataSource"/>


factory
org.apache.commons.dbcp.BasicDataSourceFactory



maxActive
100



maxIdle
30



maxWait
10000



username
sa


password




driverClassName
com.microsoft.jdbc.sqlserver.SQLServerDriver



url
jdbc:microsoft:sqlserver://localhost:1433;databasename=Northwind



注意:我本地的数据库的sa的密码为空,数据库使用的是Northwind,我的目录名DBTest,他的目录是D:\rautinee work\db\
打开DBTest下面的web.xml文件,用下面的代码替换原来的内容

"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

MSSql server Test App

DB Connection
jdbc/TestDB
javax.sql.DataSource
Container


ok,配置完成,下面的工作是需要编写两个文件测试一下,连接是否成功。
这里我用了http://jakarta.apache.org上面的例子
首先是bean文件
package foo;
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
public class DBTest {
String foo = "Not Connected";
int bar = -1;
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.getInt("OrderID");
}
conn.close();
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
public String getFoo() { return foo; }
public int getBar() { return bar;}
}
然后是index.jsp文件


DB Test


<%
foo.DBTest tst = new foo.DBTest();
tst.init();
%>

Ms sql server 2000 java search Results


Foo <%= tst.getFoo() %>

Bar <%= tst.getBar() %>


‘www.knowsky.com
编译运行,如果不出意外,应该检索到一条记录,
我的ie中显示的是
Ms sql server 2000 java search Results
Foo VINET
Bar 10248
ok,配制成功!
参考文档:
http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.html 上面有mysql和oracle8i的连接教程,有兴趣的朋友可以上去看一下。