jar包:
需要用到collections、dbcp和pool类库
独立jar包下载:
dbcp包:http://commons.apache.org/dbcp/download_dbcp.cgi
pool包:http://commons.apache.org/pool/download_pool.cgi
commons-collections.jar可在Tomcat下得到。
另:tomcat6带的tomcat-dbcp.jar包含了collections、dbcp和pool类库
示例:(主要代码取自DBCP API)
package dbcp;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;
import org.apache.commons.dbcp.datasources.SharedPoolDataSource;
public class DbcpConnPool {
private static DataSource ds;
static {
DriverAdapterCPDS cpds = new DriverAdapterCPDS();
try {
cpds.setDriver("com.microsoft.jdbc.sqlserver.SQLServerDriver");
cpds.setUrl("jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sample");
cpds.setUser("sa");
cpds.setPassword("123");
SharedPoolDataSource tds = new SharedPoolDataSource();
tds.setConnectionPoolDataSource(cpds);
tds.setMaxActive(10);
tds.setMaxWait(50);
ds = tds;
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection conn = null;
try{
conn = ds.getConnection();
}catch(Exception e){
}
return conn;
}
public static void main(String[] args){
Connection con = null;
try
{
con = DbcpConnPool.getConnection();
// ...
// use the connection
// ...
}
finally
{
if (con != null)
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
如果给你带来帮助,欢迎微信或支付宝扫一扫,赞一下。