1. 在tomcat服务器目录下面的conf中找到一个叫Context.xml的配置文件,在其中加入以下代码
<
Resource
name
="jdbc/books"
auth ="Container" type ="javax.sql.DataSource" maxActive ="100"
maxIdle ="30" maxWait ="10000" username ="sa" password ="120010"
driverClassName ="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url ="jdbc:sqlserver://localhost:1433;DatabaseName=news" />
auth ="Container" type ="javax.sql.DataSource" maxActive ="100"
maxIdle ="30" maxWait ="10000" username ="sa" password ="120010"
driverClassName ="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url ="jdbc:sqlserver://localhost:1433;DatabaseName=news" />
参数含义: JNDI (java naming and directory interface): Java 命名和目录接口
name
|
指定
Resource
的
JNDI
名称
|
auth
|
指定管理
Resource
的
Manager
(
Container
:由容器创
建和管理|
Application
:由
Web
应用创建和管理)
|
type
|
指定
Resource
所属的
Java
类
|
maxActive
|
指定连接池中处于活动状态的数据库连接的最大数目
|
maxIdle
|
指定连接池中处于空闲状态的数据库连接的最大数目
|
maxWait
|
指定连接池中的连接处于空闲的最长时间,超过这个
时间会抛出异常,取值为-1,表示可以无限期等待
|
2. 第二步将 数据驱动.jar 放入tomcat目录下的lib或common\lib下面
3. 第三步,打开应用程序的 Web.xml文件,添加以下配置
<
resource-ref
>
< res-ref-name >jdbc/books </ res-ref-name >
< res-type >javax.sql.DataSource </ res-type >
< res-auth >Container </ res-auth >
</ resource-ref >
< res-ref-name >jdbc/books </ res-ref-name >
< res-type >javax.sql.DataSource </ res-type >
< res-auth >Container </ res-auth >
</ resource-ref >
节点数据来源于Context.xml里面设置的数据
4. 在java文件中先导入以下包
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
将原来的数据库连接操作
Class.forName("oracle.jdbc.driver.OracleDriver");
if( conn == null || conn.isClosed() )
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL",
"system",
"accp");
if( conn == null || conn.isClosed() )
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL",
"system",
"accp");
换成
Context c =
new InitialContext();
DataSource ds = (DataSource)c.lookup("java:comp/env/jdbc/books");
conn = ds.getConnection();
DataSource ds = (DataSource)c.lookup("java:comp/env/jdbc/books");
conn = ds.getConnection();
记得要捕获 NamingException 与 SQLException 异常
使用连接池的好处是
数据库操作性能得到提升
通过连接池管理数据库的连接与释放、提高了系统资源的使用效率