3

我有一个连接到数据库并检索数据表的 SQL 类。我知道 SqlConnection 必须在完成后处理。我知道这可以使用块来完成,但是将调用放在此类的析构函数中using是否也可以接受?Dispose()

这是我的代码:

public class SQLEng
{

    //Connection String Property
    //Must be set to establish a connection to the database
    public string ConnectionString{ get; set; }
    SqlConnection _Conn;

    //Overridden Constructor enforcing the Connection string to be set when created
    public SQLEng(string connectionString)
    {
        ConnectionString = connectionString;
        _Conn = new SqlConnection(connectionString);
    }

    //ensure the SqlConnection is disposed when destructing this object
    public ~SQLEng()
    {
        _Conn.Dispose();
    }

    //various other methods to get datatables etc...
}

基本上我希望有一个类变量SqlConnection,而不是在每个访问数据库的方法中实例化SqlConnection。这是声音练习吗?

4

3 回答 3

8

SqlConnection您的设计鼓励长时间挂在(可能是打开的)上。最佳做法是在需要之前打开连接,然后在完成后立即释放(关闭和处置)它。

是的,创建新连接会产生一些开销;连接池减少了大部分处理时间。更糟糕的是在服务器上保持许多连接处于活动状态。

于 2012-04-12T02:27:24.043 回答
1

查看 Enterprise Library 的源代码(来自 MS Patterns & Practices 团队),DAAB 根据需要创建连接并尽快处理它。

public virtual int ExecuteNonQuery(DbCommand command)
{
    using (var wrapper = GetOpenConnection())
    {
        PrepareCommand(command, wrapper.Connection);
        return DoExecuteNonQuery(command);
    }
}

protected DatabaseConnectionWrapper GetOpenConnection()
{
    DatabaseConnectionWrapper connection = TransactionScopeConnections.GetConnection(this);
    return connection ?? GetWrappedConnection();
}

所以我会说这是一个最佳实践。在大多数情况下,您所做的只是将连接返回到连接池,因此连接本身并没有关闭。

于 2012-04-12T02:37:21.437 回答
0

如果您希望包装 SQL Connection 类,请实现 IDisposable 并从您自己的 Dispose() 方法中调用连接 Dispose()。更多信息在这里:

正确处理 DbConnection

至于这是否是一个好习惯——好吧,如果你所做的一切都是将 SQL 连接包装在另一个类中,我不确定你正在实现什么。您的所有方法仍然需要访问此类的实例,在这种情况下,它们可以自行访问连接对象的实例。

于 2012-04-12T02:27:15.437 回答