使用JNDI配置TOMCAT中数据库连接池的步骤(这里连接的是SqlServer2005):
1、打开tomcat安装目录下conf文件夹下的context.xml文件,在<context>节点下添加如下数据源连接:
<Resource name="jdbc/news" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="sa" password="123" driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" url="jdbc:sqlserver://localhost:1433;database=newsdb"/>
name 是创建连接时需要使用的
maxActive是最多的连接数目
maxIdle是最大的空闲连接数目
maxWait连接池中连接的最大等待时间
username是用户名
password是密码
url 是加载的驱动包
(下面的时orcl数据库链接的jndi)
<Resource name="jdbc/bam" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="bam"
password="bam" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@192.168.3.186:1521:ORCL" />
2、将数据库JAVA驱动包复制到tomcat安装目录lib文件夹下;
3、打开WEB应用程序的webroot-web-inf下的web.xml,添加如下:
<resource-ref>
<res-ref-name>jdbc/news</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
(这里的相关信息必须要和上面context.xml中的有关信息一致)
4、修改数据库操作辅助类DBCon类,修改获取数据库连接的代码:
//初始化Context对象,用于读取tomcat下的context.xml文件
Context context=new InitialContext();
//通过jndi获取数据源对象
DataSource source=(DataSource)context.lookup("java:comp/env/jdbc/news");
//通过数据源中的连接池获取空闲的数据库连接对象
con=source.getConnection();
select count(*) from v$process; //查询已连接的连接数目
select value from v$parameter where name = 'processes' //数据库默认最大的连接数目