Apache Tomcat7.02 集成了DBCP连接池,JAR文件为tomcat-dbcp.jar,以下是一个使用例子:
 1package myBean;
 2
 3import java.sql.*;
 4import javax.sql.DataSource;
 5
 6//DBCP原版包为org.apache.commons.dbcp.BasicDataSource;
 7import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
 8
 9public class test {
10    public test() {
11
12    }

13
14    public void haha() {
15        DataSource dataSource = setupDataSource("jdbc:sqlserver://LOCALHOST:1433;DatabaseName=BBS");
16        Connection conn = null;
17        Statement stmt = null;
18        ResultSet rset = null;
19        try {
20            System.out.println("Creating connection.");
21            conn = dataSource.getConnection();
22            System.out.println("Creating statement.");
23            stmt = conn.createStatement();
24            System.out.println("Executing statement.");
25            rset = stmt.executeQuery("select * from tblUserInfo");
26            System.out.println("Results:");
27            int numcols = rset.getMetaData().getColumnCount();
28            while (rset.next()) {
29                for (int i = 1; i <= numcols; i++{
30                    System.out.print("\t" + rset.getString(i));
31                }

32                System.out.println("");
33            }

34        }
 catch (SQLException e) {
35            e.printStackTrace();
36        }
 finally {
37            try {
38                if (rset != null)
39                    rset.close();
40            }
 catch (Exception e) {
41            }

42            try {
43                if (stmt != null)
44                    stmt.close();
45            }
 catch (Exception e) {
46            }

47            try {
48                if (conn != null)
49                    conn.close();
50            }
 catch (Exception e) {
51            }

52        }

53    }

54
55    public static DataSource setupDataSource(String connectURI) {
56        BasicDataSource ds = new BasicDataSource();
57        ds.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
58        ds.setUsername("sa");
59        ds.setPassword("******");
60        ds.setUrl(connectURI);
61        return ds;
62    }

63
64    public static void printDataSourceStats(DataSource ds) {
65        BasicDataSource bds = (BasicDataSource) ds;
66        System.out.println("NumActive: " + bds.getNumActive());
67        System.out.println("NumIdle: " + bds.getNumIdle());
68    }

69
70    public static void shutdownDataSource(DataSource ds) throws SQLException {
71        BasicDataSource bds = (BasicDataSource) ds;
72        bds.close();
73    }

74
75}

76