1.Tomcat 中直接使用的方法:
在conf/server.xml下的<GlobalNamingResources>节点里配置resource,例如:
<Resource name="jdbc/ens"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
testWhileIdle="true"
testOnBorrow="true"
testOnReturn="false"
validationInterval="30000"
timeBetweenEvictionRunsMillis="30000"
maxActive="100"
minIdle="10"
maxWait="10000"
initialSize="10"
removeAbandonedTimeout="60"
removeAbandoned="true"
logAbandoned="true"
minEvictableIdleTimeMillis="30000"
jmxEnabled="true"
jdbcInterceptors=
"org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
username="root"
password="123"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/ens"/>
然后,在context.xml文件的<Context></Context>节点中添加如下配置:
<ResourceLink global="jdbc/ens" name="jdbc/ens" type="javax.sql.DataSource"/>
global="jdbc/ens" 中的参数值("jdbc/ens")必须和上一段<Resource >配置中的name属性的值保持一样。name="jdbc/ens" 这个可以随便取,但是在程序中调用的时候,就应该与name的值保持一致。到这里,连接池已经配置好啦。
用JSP测试一下:
<%@ page language="java" pageEncoding="gbk"%>
<%@page import="java.sql.Connection"%>
<%@page import="javax.naming.Context"%>
<%@page import="javax.naming.InitialContext"%>
<%@page import="javax.sql.DataSource"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.ResultSet"%>
<%
//连接池的获取
Connection conn = null;
DataSource ds = null;
ResultSet rs =null;
Statement stmt = null;
Context initCtx = new InitialContext();
ds =(DataSource)initCtx.lookup("java:comp/env/jdbc/ens");
if(ds!=null){
out.println("已经获得DataSource!");
out.println("<br>");
conn = ds.getConnection();
try{
stmt = conn.createStatement();
String sql ="select * from ens_area";
rs = stmt.executeQuery(sql);
out.println("以下是从数据库中读取出来的数据:<br>");
while(rs.next()){
out.println("<br>");
out.println(rs.getString("area_name"));
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
conn.close();
rs.close();
stmt.close();
}
}
%>