使用dbcp,可以通过线程池的方式访问数据库
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public final class DBConnect {
static Log logger = LogFactory.getLog(DBConnect.class);
private DBConnect(){};
private static DBConnect instance = null;
public static synchronized final DBConnect instance(){
if(instance == null){
instance = new DBConnect();
}
return instance;
}
private BasicDataSource ds = null;
public void connect() {
if (ds == null) {
synchronized (DBConnect.class) {
if (ds == null) {
try {
ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUsername("sear");
ds.setPassword("...");
ds.setUrl("jdbc:mysql://crawler/pagecrawl?useUnicode=true&characterEncoding=UTF-8");
ds.setMaxActive(10);//设置多大活动线程数
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
}
public Connection getConnection() throws SQLException {
connect();
return ds.getConnection();
}