1. 将数据库驱动程序的JAR文件放在Tomcat的 common/lib 中;日前最新有是5.0
下载地址:http://dev.mysql.com/downloads/
2. 在web应用程序的context.xml中设置数据源链接(Tomcat目录下的conf/Catalina/localhost/目录中),例如我的dbtest.xml内容如下:
< Context path ="/dbtest"
docBase ="D:/workspace/dbtest/WebRoot"
debug ="0" >
< Resource
name ="jdbc/mysql"
type ="javax.sql.DataSource"
driverClassName ="com.mysql.jdbc.Driver"
password ="123456"
maxIdle ="2"
maxWait ="5000"
username ="root"
url ="jdbc:mysql://127.0.0.1:3306/mysql"
maxActive ="4" />
</ Context >
属性说明:
name 数据源名称,通常取”jdbc/XXX”的格式
type "javax.sql.DataSource" (不能改动)
driveClassName 数据库驱动
password 数据库用户密码
maxIdle 最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连
接将被标记为不可用,然后被释放。设为0表示无限制。
maxWait 最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示
maxActive 连接池的最大数据库连接数。设为0表示无限制。
username 数据库用户名
url 数据库连接URL,这个应该知道的吧
< 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" >
< resource-ref >
< description > DB Connection </ description >
< res-ref-name > jdbc/mysql </ res-ref-name >
< res-type > javax.sql.DataSource </ res-type >
< res-auth > Container </ res-auth >
</ resource-ref >
</ web-app >
说明:
description 描述信息;
res-ref-name 参考数据源名字,同Server.xml中的属性name;
res-type 资源类型,”javax.sql.DataSource”;
4. 至此,设置完成,下面是如何使用数据库连接池。
5.测试程序,注意此程序放置位置,按我的配置文件,这个程序就要放置在 D:/workspace/dbtest/WebRoot目录下<% @ page language = " java " import = " java.util.* " contentType = " text/html; charset=GB18030 "
pageEncoding = " GB18030 " %>
< html >< head >< title ></ title >
<%
out.print( " 开始测试: " + " <br/> " );
DataSource ds = null ;
Connection con = null ;
try {
Context initCtx = new InitialContext();
Context ctx = (Context) initCtx.lookup("java:comp/env");
//这里的数据库前文提及的Data Source URL配置里包含的数据库。
ds = (DataSource)ctx.lookup("jdbc/mysql");
con=ds.getConnection();
Statement stmt = con.createStatement();
String strSql = "select * from user";
//表中的字段读者自行添加
ResultSet rs = stmt.executeQuery(strSql);
while(rs.next()){
out.print(rs.getString(1)+"<br/>");
}
rs.close();
stmt.close();
con.close();
out.print("我的测试结束");
}
catch (Exception ex) {
out.print("出现例外,信息是:"+ ex.getMessage());
ex.printStackTrace();
}
%>
</ head >< body ></ body ></ html >
1)
org.xml.sax.SAXParseException: The reference to entity "characterEncoding" must
end with the ';' delimiter.
2006-12-12 23:55:08 org.apache.tomcat.util.digester.Digester fatalError
ムマヨリ: Parse Fatal Error at line 18 column 75: The reference to entity "character
Encoding" must end with the ';' delimiter.
org.xml.sax.SAXParseException: The reference to entity "characterEncoding" must
end with the ';' delimiter.
这个错误就是 context.xml 中设置数据源链接URL的问题,正确如下:
< name > url </ name >
< value > jdbc:mysql://localhost:3306/mysql?useUnicode=true & characterEncoding=gbk </ value >
</ parameter >
2) java.sql.SQLException: No suitable driver
这个就是context.xml中没有设置好了。