首页 > 代码库 > 编写标准的数据源

编写标准的数据源

 1 static LinkedList<Connection> list = new LinkedList<Connection>();//线程不安全的集合
 2     //线程安全的集合
 3     //连接池
 4     //static List<Connection> list =  Collections.synchronizedList(new LinkedList<Connection>());
 5     static{
 6         Properties p = new Properties();
 7         try {
 8             //加载配置文件
 9             p.load(MyDataSource.class.getClassLoader().getResourceAsStream("database.properties"));
10             Class.forName(p.getProperty("class_driver"));
11             for (int i = 0; i <10; i++) {
12                 Connection conn = DriverManager.getConnection(p.getProperty("connection_url"),p.getProperty("connection_username"),p.getProperty("connection_password"));
13                 list.add(conn);
14             }
15         
16         } catch (Exception e) {
17             // TODO Auto-generated catch block
18             e.printStackTrace();
19         } 
20     }
21 
22     @Override
23     public Connection getConnection() throws SQLException {
24         //没必要创建连接
25         //而是从集合中取
26         if (list.size()>0) {
27             //返回元素 并移除元素 
28             Connection conn = list.removeFirst();
29             return conn;
30         }else{
31             throw new SQLException("服务器忙………………");
32         }
33     }

 

编写标准的数据源