处置SQL连接

Sim*_*mon 3 c# dispose destructor

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

Herre是我的代码:

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...
}
Run Code Online (Sandbox Code Playgroud)

基本上我希望有一个类变量SqlConnection,而不是在每个访问数据库的方法中实例化SqlConnection.这听起来有效吗?

Yuc*_*uck 8

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

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