我有一个连接到数据库并检索数据表的 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/