连接池小例子
时间:2010-06-04 来源:wjxcoder
public class ConnectionManager {
private Properties props;
private static byte[] syn = new byte[4]; //同步变量
private static Hashtable dataSources = new Hashtable(); // 注意这里是 Hashtable
private String filename;
/**
* @param 字符串
* 一个配置文件的路径
* @param 配置文件【是以键值的方式的文本】
* 初始化配置 propertis
* 和datasource
*/
public ConnectionManager(String filename) {
this.filename = filename;
try {
if (!dataSources.containsKey(filename)) {
synchronized (syn) {
props = new Properties();
if (!dataSources.containsKey(filename)) {
props.load(this.getClass()
.getResourceAsStream(filename));
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(props.getProperty("jdbc-driver-class"));
ds.setUser(props.getProperty("database-user"));
ds.setPassword(props.getProperty("database-password"));
ds.setJdbcUrl(props.getProperty("database-url"));
ds.setAutoCommitOnClose(true);
dataSources.put(this.filename, ds);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 得到与数据库的连接
*
* @return Connection con
*/
public Connection getConnection() {
Connection conn = null;
try {
conn = ((DataSource)dataSources.get(this.filename)).getConnection();
} catch (Exception e) {
e.printStackTrace();
System.out.println("建立连接失败!");
}
return conn;
}
}
private Properties props;
private static byte[] syn = new byte[4]; //同步变量
private static Hashtable dataSources = new Hashtable(); // 注意这里是 Hashtable
private String filename;
/**
* @param 字符串
* 一个配置文件的路径
* @param 配置文件【是以键值的方式的文本】
* 初始化配置 propertis
* 和datasource
*/
public ConnectionManager(String filename) {
this.filename = filename;
try {
if (!dataSources.containsKey(filename)) {
synchronized (syn) {
props = new Properties();
if (!dataSources.containsKey(filename)) {
props.load(this.getClass()
.getResourceAsStream(filename));
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(props.getProperty("jdbc-driver-class"));
ds.setUser(props.getProperty("database-user"));
ds.setPassword(props.getProperty("database-password"));
ds.setJdbcUrl(props.getProperty("database-url"));
ds.setAutoCommitOnClose(true);
dataSources.put(this.filename, ds);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 得到与数据库的连接
*
* @return Connection con
*/
public Connection getConnection() {
Connection conn = null;
try {
conn = ((DataSource)dataSources.get(this.filename)).getConnection();
} catch (Exception e) {
e.printStackTrace();
System.out.println("建立连接失败!");
}
return conn;
}
}
相关阅读 更多 +