connectionpool.cs

来自「一个农村管理系统的程序 数据库那部分可能不全 大家可以」· CS 代码 · 共 106 行

CS
106
字号
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Data.Sql;
using System.Data.SqlClient;

namespace MsgSystem
{
    
    public class ConnectionPool
    {
        int capacity = 10;
        ArrayList freeConns = null;
        ArrayList usedConns = null;

        string ds = "Data Source=COMPUTER;Initial Catalog=MsgSystem;User ID=sa;Password=sql2000";
        
        public ConnectionPool(int capacity)
        {
            this.capacity = capacity;
            freeConns = new ArrayList(capacity);
            SqlConnection conn = null ;

            usedConns = new ArrayList( capacity);
            for (int i = 0; i < capacity; i++)
            {
                conn = new SqlConnection(ds);
                conn.Open();
                freeConns.Add(conn);

            }

        }

       public  int getSize()
        {
            return freeConns.Count;

        }

        public int getCapacity()
        {
            return capacity;
        }

        public SqlConnection getConnection()
        {
            SqlConnection rtn = null;
            object temp = null;

            lock( freeConns)
            {
                lock (usedConns)
                {
                    if ( freeConns.Count > 0)
                    {
                        temp = freeConns[0];
                        rtn = (SqlConnection)temp;
                        freeConns.Remove(rtn);
                        usedConns.Add(rtn);
                    }
                    else
                    {
                        rtn = null;

                    }
                }
            }

            return rtn;
        }

        public bool releaseConnection(SqlConnection conn)
        {
            bool rtn = false;
            SqlConnection temp = conn;


            lock ( freeConns)
            {

                lock ( usedConns)
                {
                    if ( !freeConns.Contains(conn) && usedConns.Contains(conn))
                    {
                        usedConns.Remove(temp);
                        freeConns.Add(temp);
                        rtn = true;
                    }
                    else
                    {
                        rtn = false;
                    }
                }
            }

            return rtn;
        }

    }



}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?