虽然.NET对数据库连接已经提供了连接池,但是,经测试,使用上述通用对象池实现的数据库连接池,效率要比直接使用.NET管理的连接池高。因为他减少了Open和Close操作,从而节省了时间。
代码如下:
public class DBPool { private class SqlConnectionObject : IDynamicObject { private SqlConnection _SqlConn; public SqlConnectionObject() { _SqlConn = null; }
#region IDynamicObject Members
public void Create(Object param) { String strConn = (String)param; _SqlConn = new SqlConnection(strConn); _SqlConn.Open(); }
public Object GetInnerObject() { // TODO: Add SqlConnectionObject.GetInnerObject implementation return _SqlConn; }
public bool IsValidate() { return ( _SqlConn != null && _SqlConn.GetHashCode() > 0 && _SqlConn.State == ConnectionState.Open ); }
public void Release() { // TODO: Add SqlConnectionObject.Release implementation _SqlConn.Close(); }
#endregion }
private ObjectPool _Connections;
public DBPool(string connection, int initcount, int capacity) { if(connection == null || connection == "" || initcount<0 || capacity < 1) { throw(new Exception("Invalid parameter!")); }
_Connections = new ObjectPool(typeof(SqlConnectionObject),connection,initcount,capacity); }
public SqlConnection GetConnection() { return (SqlConnection)_Connections.GetOne(); }
public void FreeConnection(SqlConnection sqlConn) { _Connections.FreeObject(sqlConn); }
public void Release() { _Connections.Release(); }
public int Count { get{return _Connections.CurrentSize;} }
public int UsingCount { get{return _Connections.ActiveCount;} }
public int DecreaseSize(int size) { return _Connections.DecreaseSize(size); } } // DBPool |