c# - 处理 SQL 连接

标签 c# destructor dispose

我有一个连接到数据库并检索数据表的 SQL 类。我知道完成后必须处理 SqlConnection。我知道这可以使用 using block 来完成,但是是否也可以将 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。这是合理的做法吗?

最佳答案

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

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

关于c# - 处理 SQL 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10116582/

相关文章:

c# - DetailsView 不会进入编辑模式

c# - 使用 BackgroundWorker 更新 UI 而不会卡住......?

c# - 索引(从零开始)必须大于或等于零统一

C# ASP.Net 5 配置和向后兼容类库

java - 在处理之前禁用框架

c++ - 为什么在我的析构函数中抛出时总是得到 "terminate called after throwing an instance of..."?

rust - Option<T> 是 Drop 的记录在哪里?

C++ 析构函数运行时错误 : failed to munmap

c# - 如何手动处置 RSACryptoServiceProvider?

c# - 数据表内部使用?