设置tomcat数据库连接池
[代码] server.xml
<!-- Oracle 数据库 -->
<Context path="/app1" docBase="app1" debug="1" reloadable="true" crossContext="true">
<Resource name="jdbc/orcldb" auth="Container" type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/orcldb">
<parameter><name>factory</name><value>org.apache.commons.dbcp.BasicDataSourceFactory</value></parameter>
<parameter><name>driverClassName</name><value>oracle.jdbc.driver.OracleDriver</value></parameter>
<parameter><name>url</name><value>jdbc:oracle:thin:@localhost:1521:orcl</value></parameter>
<parameter><name>username</name><value>user</value></parameter>
<parameter><name>password</name><value>pwd</value></parameter>
<parameter><name>maxActive</name><value>20</value></parameter>
<parameter><name>maxIdle</name><value>10</value></parameter>
<parameter><name>maxWait</name><value>10000</value></parameter>
</ResourceParams>
</Context>
[代码] 接下来要在WEB-INF里的web.xml里加上以下信息
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<description>oralceDB</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/orcldb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
[代码] 调用方法
/**
* 返回Oracle数据库连接 注意:红色的字体表示他要调用的连接池名,同配置
* @return Connection
* @throws SQLException
*/
public static synchronized Connection getOracleConn() throws SQLException {
try {
Context jndiCntx = new InitialContext();
DataSource ds = (DataSource)jndiCntx.lookup( "java:comp/env/jdbc/orcldb");
return ds.getConnection();
}catch (NamingException ne) {
throw new EJBException(ne);
}
}