public class SqlConnectionContainer
    {
       

 private static Dictionary<int, SqlConnection> connList = new Dictionary<int, SqlConnection>();
        private static int currentNumber = 0;
        private static readonly int maxNumber;  // 连接池链接数量的最大数

        private static string connstring;

        private static object lockObject = new object();

        public static SqlConnectionContainer(int max)
        {
            maxNumber = max;
        }

        public static DbConnection GetConnection()
        {

            lock (lockObject)  //防止 并发操作
            {

                for (int i = 0; i < connList.Count; i++)
                {
                    if (connList[i].State == ConnectionState.Closed)
                    {
                        return connList[i];
                    }
                }
                //没找到 可用的链接

                if (currentNumber > maxNumber)  //判断连接池是否满了
                {
                    throw new Exception("超过了最大连接池数量");
                }

                SqlConnection conn = new SqlConnection(connstring);
                connList.Add(connList.Count+1, conn);

                currentNumber++;
                return conn;
            }
        }
    }

 //泛型连接池类

 public class SqlConnectionContainer2<T> where T : DbConnection
    {
        private static Dictionary<int, T> connList = new Dictionary<int, T>();
        private static int currentNumber = 0;
        private static readonly int maxNumber;  // 连接池链接数量的最大数


        private static string connstring=ConfigurationManager.ConnectionStrings["Test"].ToString();

        private static object lockObject = new object();

        static  SqlConnectionContainer2()
        {
            maxNumber = 30;
        }

        public static T GetConnection()
        {

            lock (lockObject)  //防止 并发操作
            {

                for (int i = 0; i < connList.Count; i++)
                {
                    if (connList[i].State == ConnectionState.Closed)
                    {
                        return connList[i];
                    }
                }
                //没找到 可用的链接

                if (currentNumber > maxNumber)  //判断连接池是否满了
                {
                    throw new Exception("超过了最大连接池数量");
                }
                T xx =(T) Activator.CreateInstance(typeof(T));
                connList.Add(connList.Count + 1, xx);

                currentNumber++;
                return xx;
            }
        }
    }

 

posted on 2009-06-03 09:40  悲哀ing  阅读(756)  评论(0编辑  收藏  举报