首页 > 代码库 > 数据库连接池的一个例子

数据库连接池的一个例子

//--------------------------------------------------------------------------------// 文件描述:数据库连接池// 文件作者:品浩// 创建日期:2013/5/23// 修改记录: //--------------------------------------------------------------------------------using System;using System.Configuration;using System.Data.SqlClient;namespace DB.SqlServer{    internal static class SqlConnectionPool    {        /// <summary>        /// 全局数据库连接字符串        /// </summary>        static internal string ConnectionString        {            get            {                if (ConfigurationManager.ConnectionStrings["ConnectionString"] != null)                    return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;                else                    throw new Exception("系统配置文件中数据库配置节有误,请检查!");            }        }        /// <summary>        /// 连接池对象,默认池内个数设置为10        /// </summary>        static SqlConnection[] ConnectionPool = new SqlConnection[10];        /// <summary>        /// 构造函数初始化数据库连接池        /// </summary>        static SqlConnectionPool()        {            for (int i = 0; i < ConnectionPool.Length; i++)            {                ConnectionPool[i] = new SqlConnection(ConnectionString);            }        }        /// <summary>        /// 从数据库连接池里获取一个连接实例        /// </summary>        /// <returns></returns>        internal static SqlConnection GetInstance()        {            SqlConnection conn = null;            for (int i = 0; i < ConnectionPool.Length; i++)            {                if (ConnectionPool[i] != null)                {                    conn = ConnectionPool[i];                    ConnectionPool[i] = null;                    break;                }            }            if (conn == null)            {                return new SqlConnection(ConnectionString);            }            else return conn;        }        /// <summary>        /// 将一个连接返回到池中        /// </summary>        /// <param name="conn"></param>        internal static void PutInstance(SqlConnection conn)        {            for (int i = 0; i < ConnectionPool.Length; i++)            {                if (ConnectionPool[i] == null)                {                    ConnectionPool[i] = conn;                    break;                }            }            conn = null;        }        //end class    }}