一.DBCP 是 Apache 软件基金组织下的开源连接池实现,使用DBCP数据源,应用程序应在系统中增加如下两个jar 文件:
• Commons-dbcp.jar:连接池的实现
• Commons-pool.jar:连接池实现的依赖库
二.Tomcat 的连接池正是采用该连接池来实现的。该数据库连接池既可以与应用服务器整合使用,也可由应用程序独立使用。
三.使用DBCP示例代码
static{
InputStream in = JdbcUtil.class.getClassLoader().
getResourceAsStream("dbcpconfig.properties");
Properties prop = new Properties();
prop.load(in);
BasicDataSourceFactory factory = newBasicDataSourceFactory();
dataSource =factory.createDataSource(prop);
}
<Context reloadable="true"> <WatchedResource>WEB-INF/web.xml</WatchedResource> <Resource name="jdbc/ins" auth="Container" type="javax.sql.DataSource" factory="org.apache.commons.dbcp.BasicDataSource" username="sa" password="3891291" driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver" url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=newssystem;SelectMethod=cursor" maxActive="50" maxIdle="20"/> </Context>
默认factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
测试1
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/ins");
Connection conn = ds.getConnection();
if(!conn.isClosed())
out.println("資料庫連線測試成功!");
conn.close();
} catch (Exception e) {
e.printStackTrace();
out.println(e);
}
测试2
Context initContext;
try {
Context context=new InitialContext();
DataSource ds=(DataSource) context.lookup("java:/comp/env/jdbc/tango");
// "java:/comp/env/"是固定写法,后面接的是 context.xml中的Resource中name属性的值
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet set = stmt.executeQuery("SELECT id,name,age FROM user_lzy");
while(set.next()){
System.out.println(set.getString("name"));
}
//etc.
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}