Chinaunix首页 | 论坛 | 博客
  • 博客访问: 402668
  • 博文数量: 126
  • 博客积分: 3002
  • 博客等级: 少校
  • 技术积分: 1210
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-30 15:04
文章分类

全部博文(126)

文章存档

2012年(14)

2011年(63)

2010年(36)

2009年(13)

分类: Java

2010-06-04 17:45:53

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;

    }
}
阅读(943) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~