第一步:对于tomcat5.0以上版本配置,不建议在server.xml中配置,这里以tomcat5.5为例
在conf目录下的context.xml文件中的<Context>标签下配置如下信息:
<!--Configuration database yangchen 2012-4-7 -->
<Resource name="memoryDataSource"
auth="Container"
type="javax.sql.DataSource"
maxActive="20"
maxIdel="10"
maxWait="1000"
username="root"
password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test" />
各参数说明:
name:数据源名称,这里可以任意取名
auth:这里为Container意思是数据源由容器管理
maxActive:最大连接数为0表示不受限制
maxIdle:最大空闲连接数为0表示不受限制
maxWait:设置空闲等待时间,毫秒,-1代表无限
第二步:在conf目录下的web.xml文件中的</web-app>标签上配置如下信息:
<!--Configuration Database reference to context.xml 2012-4-7 yangchen -->
<resource-ref>
<res-ref-name>memoryDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
第三步,把数据库连接的驱动jar包copy到common\lib目录下
第四步,可以随便写个测试类,这是在jsp页面中写的,如下:
<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<%
Connection conn=null;
DataSource ds=null;
Context context =newInitialContext();
ds = (DataSource)context.lookup("java:comp/env/memoryDataSource");
conn=ds.getConnection();
System.out.println(conn);
%>
需要说明的是tomcat的配置,代表中必须写java:comp/env。
第五步,出现类似于这样的信息:
jdbc:mysql://localhost:3306/test, UserName=root@localhost, MySQL-ABJDBC Driver
表示链接成功。