欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

IDbConnection 正确的链接关闭与打开

程序员文章站 2024-01-14 21:12:58
...

为啥要写IDbConnection的正常关闭与开启的写法,用Ado.net的人都经历过,我想通用一个sqlhelper,然而当链接数据库的连接数过多的时候,会报错。

IDbConnection 的正规链接的写法

public class ShareConnection
{
    private IDbConnection _sharedConnection;
    private DbProviderFactory _factory;

    private bool ShouldCloseConnectionAutomatically{get;set;}

    public ShareConnection(string providerName)
    {
        _factory=DbProviderFactories.GetFactory(providerName);
    }
    /// <summary>
    /// 打开共享链接
    /// </summary>
    public void OpenSharedConnection()
    {
        OpenSharedConnectionImplement(false);
    }
    private void OpenSharedConnectionImplement(bool isInternal)
    {
        //这里注意数据库链接状态的判断
        if(_sharedConnection!=null&&_sharedConnection.State!=ConnectionState.Broken&&_sharedConnection.State!=ConnectionState.Closed)
            return;
        ShouldCloseConnectionAutomatically=isInternal;

        _sharedConnection=_factory.CreateConnection();
        if(_sharedConnection==null) throw new Exception("Sql connection failed to configure providername");
        if(_sharedConnection.State==ConnectionState.Broken)
        {
            _sharedConnection.Close();
        }
        if(_sharedConnection.State==ConnectionState.Closed)
        {
            _sharedConnection.Open();
        }
    }
    private void CloseSharedConnectionInternal()
    {
        if(ShouldCloseConnectionAutomatically)
            CloseSharedConnection();
    }
    /// <summary>
    /// 关闭共享链接
    /// </summary>
    public void CloseSharedConnection()
    {
        if(_sharedConnection==null) return;

        _sharedConnection.Close();
        _sharedConnection.Dispose();
        _sharedConnection=null;
    }
}

关于事务的锁设置与事务的管理,下一篇再讲

相关标签: ado.net